chore(package): update jasmine to version 3.0.0 (#4553)

* chore(package): update jasmine to version 3.0.0

Closes #4547

* Fixes failing tests for jasmine 3.0

Starting 3.0, done(something) will fail

* Update tests so they dont leverage var, but let and const

With jasmine 3.0, the randomization engine was making the test fails because of the scope of `var`

* Remove randomizer

* Use same adapter for PG tests, drop table to ensure the tests dont side effect
This commit is contained in:
Florent Vilmart
2018-02-17 09:55:30 -05:00
committed by GitHub
parent 8ec7785d53
commit b754d51e8e
81 changed files with 2698 additions and 2704 deletions

View File

@@ -58,7 +58,7 @@
"eslint-plugin-flowtype": "^2.39.1", "eslint-plugin-flowtype": "^2.39.1",
"flow-bin": "^0.66.0", "flow-bin": "^0.66.0",
"gaze": "1.1.2", "gaze": "1.1.2",
"jasmine": "2.9.0", "jasmine": "3.0.0",
"jasmine-spec-reporter": "^4.1.0", "jasmine-spec-reporter": "^4.1.0",
"mongodb-runner": "3.6.1", "mongodb-runner": "3.6.1",
"nodemon": "1.15.0", "nodemon": "1.15.0",

View File

@@ -28,6 +28,7 @@
"arrayContains": true "arrayContains": true
}, },
"rules": { "rules": {
"no-console": [0] "no-console": [0],
"no-var": "error"
} }
} }

View File

@@ -2,7 +2,7 @@
const Config = require("../src/Config"); const Config = require("../src/Config");
var loginWithWrongCredentialsShouldFail = function(username, password) { const loginWithWrongCredentialsShouldFail = function(username, password) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Parse.User.logIn(username, password) Parse.User.logIn(username, password)
.then(() => reject('login should have failed')) .then(() => reject('login should have failed'))
@@ -16,7 +16,7 @@ var loginWithWrongCredentialsShouldFail = function(username, password) {
}); });
}; };
var isAccountLockoutError = function(username, password, duration, waitTime) { const isAccountLockoutError = function(username, password, duration, waitTime) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
setTimeout(() => { setTimeout(() => {
Parse.User.logIn(username, password) Parse.User.logIn(username, password)
@@ -40,7 +40,7 @@ describe("Account Lockout Policy: ", () => {
publicServerURL: 'http://localhost:1337/1', publicServerURL: 'http://localhost:1337/1',
}) })
.then(() => { .then(() => {
var user = new Parse.User(); const user = new Parse.User();
user.setUsername('username1'); user.setUsername('username1');
user.setPassword('password'); user.setPassword('password');
return user.signUp(null); return user.signUp(null);
@@ -215,7 +215,7 @@ describe("Account Lockout Policy: ", () => {
publicServerURL: "http://localhost:8378/1" publicServerURL: "http://localhost:8378/1"
}) })
.then(() => { .then(() => {
var user = new Parse.User(); const user = new Parse.User();
user.setUsername("username2"); user.setUsername("username2");
user.setPassword("failedLoginAttemptsThreshold"); user.setPassword("failedLoginAttemptsThreshold");
return user.signUp(); return user.signUp();
@@ -248,7 +248,7 @@ describe("Account Lockout Policy: ", () => {
publicServerURL: "http://localhost:8378/1" publicServerURL: "http://localhost:8378/1"
}) })
.then(() => { .then(() => {
var user = new Parse.User(); const user = new Parse.User();
user.setUsername("username3"); user.setUsername("username3");
user.setPassword("failedLoginAttemptsThreshold"); user.setPassword("failedLoginAttemptsThreshold");
return user.signUp(); return user.signUp();
@@ -285,7 +285,7 @@ describe("Account Lockout Policy: ", () => {
publicServerURL: "http://localhost:8378/1" publicServerURL: "http://localhost:8378/1"
}) })
.then(() => { .then(() => {
var user = new Parse.User(); const user = new Parse.User();
user.setUsername("username4"); user.setUsername("username4");
user.setPassword("correct password"); user.setPassword("correct password");
return user.signUp(); return user.signUp();

View File

@@ -1,9 +1,9 @@
var AdaptableController = require("../src/Controllers/AdaptableController").AdaptableController; const AdaptableController = require("../src/Controllers/AdaptableController").AdaptableController;
var FilesAdapter = require("../src/Adapters/Files/FilesAdapter").default; const FilesAdapter = require("../src/Adapters/Files/FilesAdapter").default;
var FilesController = require("../src/Controllers/FilesController").FilesController; const FilesController = require("../src/Controllers/FilesController").FilesController;
var MockController = function(options) { const MockController = function(options) {
AdaptableController.call(this, options); AdaptableController.call(this, options);
} }
MockController.prototype = Object.create(AdaptableController.prototype); MockController.prototype = Object.create(AdaptableController.prototype);
@@ -11,8 +11,8 @@ MockController.prototype.constructor = AdaptableController;
describe("AdaptableController", ()=>{ describe("AdaptableController", ()=>{
it("should use the provided adapter", (done) => { it("should use the provided adapter", (done) => {
var adapter = new FilesAdapter(); const adapter = new FilesAdapter();
var controller = new FilesController(adapter); const controller = new FilesController(adapter);
expect(controller.adapter).toBe(adapter); expect(controller.adapter).toBe(adapter);
// make sure _adapter is private // make sure _adapter is private
expect(controller._adapter).toBe(undefined); expect(controller._adapter).toBe(undefined);
@@ -23,7 +23,7 @@ describe("AdaptableController", ()=>{
}); });
it("should throw when creating a new mock controller", (done) => { it("should throw when creating a new mock controller", (done) => {
var adapter = new FilesAdapter(); const adapter = new FilesAdapter();
expect(() => { expect(() => {
new MockController(adapter); new MockController(adapter);
}).toThrow(); }).toThrow();
@@ -32,9 +32,9 @@ describe("AdaptableController", ()=>{
it("should fail setting the wrong adapter to the controller", (done) => { it("should fail setting the wrong adapter to the controller", (done) => {
function WrongAdapter() {} function WrongAdapter() {}
var adapter = new FilesAdapter(); const adapter = new FilesAdapter();
var controller = new FilesController(adapter); const controller = new FilesController(adapter);
var otherAdapter = new WrongAdapter(); const otherAdapter = new WrongAdapter();
expect(() => { expect(() => {
controller.adapter = otherAdapter; controller.adapter = otherAdapter;
}).toThrow(); }).toThrow();
@@ -43,7 +43,7 @@ describe("AdaptableController", ()=>{
it("should fail to instantiate a controller with wrong adapter", (done) => { it("should fail to instantiate a controller with wrong adapter", (done) => {
function WrongAdapter() {} function WrongAdapter() {}
var adapter = new WrongAdapter(); const adapter = new WrongAdapter();
expect(() => { expect(() => {
new FilesController(adapter); new FilesController(adapter);
}).toThrow(); }).toThrow();
@@ -58,7 +58,7 @@ describe("AdaptableController", ()=>{
}); });
it("should accept an object adapter", (done) => { it("should accept an object adapter", (done) => {
var adapter = { const adapter = {
createFile: function() { }, createFile: function() { },
deleteFile: function() { }, deleteFile: function() { },
getFileData: function() { }, getFileData: function() { },
@@ -77,7 +77,7 @@ describe("AdaptableController", ()=>{
AGoodAdapter.prototype.getFileData = function() { }; AGoodAdapter.prototype.getFileData = function() { };
AGoodAdapter.prototype.getFileLocation = function() { }; AGoodAdapter.prototype.getFileLocation = function() { };
var adapter = new AGoodAdapter(); const adapter = new AGoodAdapter();
expect(() => { expect(() => {
new FilesController(adapter); new FilesController(adapter);
}).not.toThrow(); }).not.toThrow();

View File

@@ -1,16 +1,16 @@
var loadAdapter = require("../src/Adapters/AdapterLoader").loadAdapter; const loadAdapter = require("../src/Adapters/AdapterLoader").loadAdapter;
var FilesAdapter = require("@parse/fs-files-adapter").default; const FilesAdapter = require("@parse/fs-files-adapter").default;
var S3Adapter = require("@parse/s3-files-adapter").default; const S3Adapter = require("@parse/s3-files-adapter").default;
var ParsePushAdapter = require("@parse/push-adapter").default; const ParsePushAdapter = require("@parse/push-adapter").default;
const Config = require('../src/Config'); const Config = require('../src/Config');
describe("AdapterLoader", ()=>{ describe("AdapterLoader", ()=>{
it("should instantiate an adapter from string in object", (done) => { it("should instantiate an adapter from string in object", (done) => {
var adapterPath = require('path').resolve("./spec/MockAdapter"); const adapterPath = require('path').resolve("./spec/MockAdapter");
var adapter = loadAdapter({ const adapter = loadAdapter({
adapter: adapterPath, adapter: adapterPath,
options: { options: {
key: "value", key: "value",
@@ -25,16 +25,16 @@ describe("AdapterLoader", ()=>{
}); });
it("should instantiate an adapter from string", (done) => { it("should instantiate an adapter from string", (done) => {
var adapterPath = require('path').resolve("./spec/MockAdapter"); const adapterPath = require('path').resolve("./spec/MockAdapter");
var adapter = loadAdapter(adapterPath); const adapter = loadAdapter(adapterPath);
expect(adapter instanceof Object).toBe(true); expect(adapter instanceof Object).toBe(true);
done(); done();
}); });
it("should instantiate an adapter from string that is module", (done) => { it("should instantiate an adapter from string that is module", (done) => {
var adapterPath = require('path').resolve("./src/Adapters/Files/FilesAdapter"); const adapterPath = require('path').resolve("./src/Adapters/Files/FilesAdapter");
var adapter = loadAdapter({ const adapter = loadAdapter({
adapter: adapterPath adapter: adapterPath
}); });
@@ -47,7 +47,7 @@ describe("AdapterLoader", ()=>{
}); });
it("should instantiate an adapter from npm module", (done) => { it("should instantiate an adapter from npm module", (done) => {
var adapter = loadAdapter({ const adapter = loadAdapter({
module: '@parse/fs-files-adapter' module: '@parse/fs-files-adapter'
}); });
@@ -60,7 +60,7 @@ describe("AdapterLoader", ()=>{
}); });
it("should instantiate an adapter from function/Class", (done) => { it("should instantiate an adapter from function/Class", (done) => {
var adapter = loadAdapter({ const adapter = loadAdapter({
adapter: FilesAdapter adapter: FilesAdapter
}); });
expect(adapter instanceof FilesAdapter).toBe(true); expect(adapter instanceof FilesAdapter).toBe(true);
@@ -68,52 +68,52 @@ describe("AdapterLoader", ()=>{
}); });
it("should instantiate the default adapter from Class", (done) => { it("should instantiate the default adapter from Class", (done) => {
var adapter = loadAdapter(null, FilesAdapter); const adapter = loadAdapter(null, FilesAdapter);
expect(adapter instanceof FilesAdapter).toBe(true); expect(adapter instanceof FilesAdapter).toBe(true);
done(); done();
}); });
it("should use the default adapter", (done) => { it("should use the default adapter", (done) => {
var defaultAdapter = new FilesAdapter(); const defaultAdapter = new FilesAdapter();
var adapter = loadAdapter(null, defaultAdapter); const adapter = loadAdapter(null, defaultAdapter);
expect(adapter instanceof FilesAdapter).toBe(true); expect(adapter instanceof FilesAdapter).toBe(true);
done(); done();
}); });
it("should use the provided adapter", (done) => { it("should use the provided adapter", (done) => {
var originalAdapter = new FilesAdapter(); const originalAdapter = new FilesAdapter();
var adapter = loadAdapter(originalAdapter); const adapter = loadAdapter(originalAdapter);
expect(adapter).toBe(originalAdapter); expect(adapter).toBe(originalAdapter);
done(); done();
}); });
it("should fail loading an improperly configured adapter", (done) => { it("should fail loading an improperly configured adapter", (done) => {
var Adapter = function(options) { const Adapter = function(options) {
if (!options.foo) { if (!options.foo) {
throw "foo is required for that adapter"; throw "foo is required for that adapter";
} }
} }
var adapterOptions = { const adapterOptions = {
param: "key", param: "key",
doSomething: function() {} doSomething: function() {}
}; };
expect(() => { expect(() => {
var adapter = loadAdapter(adapterOptions, Adapter); const adapter = loadAdapter(adapterOptions, Adapter);
expect(adapter).toEqual(adapterOptions); expect(adapter).toEqual(adapterOptions);
}).not.toThrow("foo is required for that adapter"); }).not.toThrow("foo is required for that adapter");
done(); done();
}); });
it("should load push adapter from options", (done) => { it("should load push adapter from options", (done) => {
var options = { const options = {
android: { android: {
senderId: 'yolo', senderId: 'yolo',
apiKey: 'yolo' apiKey: 'yolo'
} }
} }
expect(() => { expect(() => {
var adapter = loadAdapter(undefined, ParsePushAdapter, options); const adapter = loadAdapter(undefined, ParsePushAdapter, options);
expect(adapter.constructor).toBe(ParsePushAdapter); expect(adapter.constructor).toBe(ParsePushAdapter);
expect(adapter).not.toBe(undefined); expect(adapter).not.toBe(undefined);
}).not.toThrow(); }).not.toThrow();
@@ -121,8 +121,8 @@ describe("AdapterLoader", ()=>{
}); });
it("should load custom push adapter from string (#3544)", (done) => { it("should load custom push adapter from string (#3544)", (done) => {
var adapterPath = require('path').resolve("./spec/MockPushAdapter"); const adapterPath = require('path').resolve("./spec/MockPushAdapter");
var options = { const options = {
ios: { ios: {
bundleId: 'bundle.id' bundleId: 'bundle.id'
} }
@@ -145,9 +145,9 @@ describe("AdapterLoader", ()=>{
}); });
it("should load S3Adapter from direct passing", (done) => { it("should load S3Adapter from direct passing", (done) => {
var s3Adapter = new S3Adapter("key", "secret", "bucket") const s3Adapter = new S3Adapter("key", "secret", "bucket")
expect(() => { expect(() => {
var adapter = loadAdapter(s3Adapter, FilesAdapter); const adapter = loadAdapter(s3Adapter, FilesAdapter);
expect(adapter).toBe(s3Adapter); expect(adapter).toBe(s3Adapter);
}).not.toThrow(); }).not.toThrow();
done(); done();

View File

@@ -16,7 +16,7 @@ describe('AnalyticsController', () => {
}) })
}).then(() => { }).then(() => {
expect(analyticsAdapter.trackEvent).toHaveBeenCalled(); expect(analyticsAdapter.trackEvent).toHaveBeenCalled();
var lastCall = analyticsAdapter.trackEvent.calls.first(); const lastCall = analyticsAdapter.trackEvent.calls.first();
const args = lastCall.args; const args = lastCall.args;
expect(args[0]).toEqual('MyEvent'); expect(args[0]).toEqual('MyEvent');
expect(args[1]).toEqual({ expect(args[1]).toEqual({
@@ -44,7 +44,7 @@ describe('AnalyticsController', () => {
}) })
}).then(() => { }).then(() => {
expect(analyticsAdapter.appOpened).toHaveBeenCalled(); expect(analyticsAdapter.appOpened).toHaveBeenCalled();
var lastCall = analyticsAdapter.appOpened.calls.first(); const lastCall = analyticsAdapter.appOpened.calls.first();
const args = lastCall.args; const args = lastCall.args;
expect(args[0]).toEqual({ expect(args[0]).toEqual({
dimensions: { dimensions: {

View File

@@ -1,20 +1,20 @@
var auth = require('../src/Auth'); const auth = require('../src/Auth');
var Config = require('../src/Config'); const Config = require('../src/Config');
var rest = require('../src/rest'); const rest = require('../src/rest');
var AudiencesRouter = require('../src/Routers/AudiencesRouter').AudiencesRouter; const AudiencesRouter = require('../src/Routers/AudiencesRouter').AudiencesRouter;
describe('AudiencesRouter', () => { describe('AudiencesRouter', () => {
it('uses find condition from request.body', (done) => { it('uses find condition from request.body', (done) => {
var config = Config.get('test'); const config = Config.get('test');
var androidAudienceRequest = { const androidAudienceRequest = {
'name': 'Android Users', 'name': 'Android Users',
'query': '{ "test": "android" }' 'query': '{ "test": "android" }'
}; };
var iosAudienceRequest = { const iosAudienceRequest = {
'name': 'Iphone Users', 'name': 'Iphone Users',
'query': '{ "test": "ios" }' 'query': '{ "test": "ios" }'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: { body: {
@@ -26,7 +26,7 @@ describe('AudiencesRouter', () => {
info: {} info: {}
}; };
var router = new AudiencesRouter(); const router = new AudiencesRouter();
rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest)
.then(() => { .then(() => {
return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest);
@@ -35,7 +35,7 @@ describe('AudiencesRouter', () => {
return router.handleFind(request); return router.handleFind(request);
}) })
.then((res) => { .then((res) => {
var results = res.response.results; const results = res.response.results;
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
done(); done();
}) })
@@ -46,16 +46,16 @@ describe('AudiencesRouter', () => {
}); });
it('uses find condition from request.query', (done) => { it('uses find condition from request.query', (done) => {
var config = Config.get('test'); const config = Config.get('test');
var androidAudienceRequest = { const androidAudienceRequest = {
'name': 'Android Users', 'name': 'Android Users',
'query': '{ "test": "android" }' 'query': '{ "test": "android" }'
}; };
var iosAudienceRequest = { const iosAudienceRequest = {
'name': 'Iphone Users', 'name': 'Iphone Users',
'query': '{ "test": "ios" }' 'query': '{ "test": "ios" }'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: {}, body: {},
@@ -67,7 +67,7 @@ describe('AudiencesRouter', () => {
info: {} info: {}
}; };
var router = new AudiencesRouter(); const router = new AudiencesRouter();
rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest)
.then(() => { .then(() => {
return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest);
@@ -76,7 +76,7 @@ describe('AudiencesRouter', () => {
return router.handleFind(request); return router.handleFind(request);
}) })
.then((res) => { .then((res) => {
var results = res.response.results; const results = res.response.results;
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
done(); done();
}) })
@@ -87,16 +87,16 @@ describe('AudiencesRouter', () => {
}); });
it('query installations with limit = 0', (done) => { it('query installations with limit = 0', (done) => {
var config = Config.get('test'); const config = Config.get('test');
var androidAudienceRequest = { const androidAudienceRequest = {
'name': 'Android Users', 'name': 'Android Users',
'query': '{ "test": "android" }' 'query': '{ "test": "android" }'
}; };
var iosAudienceRequest = { const iosAudienceRequest = {
'name': 'Iphone Users', 'name': 'Iphone Users',
'query': '{ "test": "ios" }' 'query': '{ "test": "ios" }'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: {}, body: {},
@@ -107,7 +107,7 @@ describe('AudiencesRouter', () => {
}; };
Config.get('test'); Config.get('test');
var router = new AudiencesRouter(); const router = new AudiencesRouter();
rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest)
.then(() => { .then(() => {
return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest);
@@ -116,7 +116,7 @@ describe('AudiencesRouter', () => {
return router.handleFind(request); return router.handleFind(request);
}) })
.then((res) => { .then((res) => {
var response = res.response; const response = res.response;
expect(response.results.length).toEqual(0); expect(response.results.length).toEqual(0);
done(); done();
}) })
@@ -127,16 +127,16 @@ describe('AudiencesRouter', () => {
}); });
it('query installations with count = 1', done => { it('query installations with count = 1', done => {
var config = Config.get('test'); const config = Config.get('test');
var androidAudienceRequest = { const androidAudienceRequest = {
'name': 'Android Users', 'name': 'Android Users',
'query': '{ "test": "android" }' 'query': '{ "test": "android" }'
}; };
var iosAudienceRequest = { const iosAudienceRequest = {
'name': 'Iphone Users', 'name': 'Iphone Users',
'query': '{ "test": "ios" }' 'query': '{ "test": "ios" }'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: {}, body: {},
@@ -146,12 +146,12 @@ describe('AudiencesRouter', () => {
info: {} info: {}
}; };
var router = new AudiencesRouter(); const router = new AudiencesRouter();
rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest)
.then(() => rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest)) .then(() => rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest))
.then(() => router.handleFind(request)) .then(() => router.handleFind(request))
.then((res) => { .then((res) => {
var response = res.response; const response = res.response;
expect(response.results.length).toEqual(2); expect(response.results.length).toEqual(2);
expect(response.count).toEqual(2); expect(response.count).toEqual(2);
done(); done();
@@ -163,16 +163,16 @@ describe('AudiencesRouter', () => {
}); });
it('query installations with limit = 0 and count = 1', (done) => { it('query installations with limit = 0 and count = 1', (done) => {
var config = Config.get('test'); const config = Config.get('test');
var androidAudienceRequest = { const androidAudienceRequest = {
'name': 'Android Users', 'name': 'Android Users',
'query': '{ "test": "android" }' 'query': '{ "test": "android" }'
}; };
var iosAudienceRequest = { const iosAudienceRequest = {
'name': 'Iphone Users', 'name': 'Iphone Users',
'query': '{ "test": "ios" }' 'query': '{ "test": "ios" }'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: {}, body: {},
@@ -183,7 +183,7 @@ describe('AudiencesRouter', () => {
info: {} info: {}
}; };
var router = new AudiencesRouter(); const router = new AudiencesRouter();
rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest) rest.create(config, auth.nobody(config), '_Audience', androidAudienceRequest)
.then(() => { .then(() => {
return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest);
@@ -192,7 +192,7 @@ describe('AudiencesRouter', () => {
return router.handleFind(request); return router.handleFind(request);
}) })
.then((res) => { .then((res) => {
var response = res.response; const response = res.response;
expect(response.results.length).toEqual(0); expect(response.results.length).toEqual(0);
expect(response.count).toEqual(2); expect(response.count).toEqual(2);
done(); done();

View File

@@ -1,11 +1,11 @@
describe('Auth', () => { describe('Auth', () => {
var Auth = require('../src/Auth.js').Auth; const Auth = require('../src/Auth.js').Auth;
describe('getUserRoles', () => { describe('getUserRoles', () => {
var auth; let auth;
var config; let config;
var currentRoles = null; let currentRoles = null;
var currentUserId = 'userId'; const currentUserId = 'userId';
beforeEach(() => { beforeEach(() => {
currentRoles = ['role:userId']; currentRoles = ['role:userId'];
@@ -33,10 +33,10 @@ describe('Auth', () => {
it('should get user roles from the cache', (done) => { it('should get user roles from the cache', (done) => {
auth.getUserRoles() auth.getUserRoles()
.then((roles) => { .then((roles) => {
var firstSet = config.cacheController.role.set.calls.first(); const firstSet = config.cacheController.role.set.calls.first();
expect(firstSet).toEqual(undefined); expect(firstSet).toEqual(undefined);
var firstGet = config.cacheController.role.get.calls.first(); const firstGet = config.cacheController.role.get.calls.first();
expect(firstGet.args[0]).toEqual(currentUserId); expect(firstGet.args[0]).toEqual(currentUserId);
expect(roles).toEqual(currentRoles); expect(roles).toEqual(currentRoles);
done(); done();
@@ -44,7 +44,7 @@ describe('Auth', () => {
}); });
it('should only query the roles once', (done) => { it('should only query the roles once', (done) => {
var loadRolesSpy = spyOn(auth, '_loadRoles').and.callThrough(); const loadRolesSpy = spyOn(auth, '_loadRoles').and.callThrough();
auth.getUserRoles() auth.getUserRoles()
.then((roles) => { .then((roles) => {
expect(roles).toEqual(currentRoles); expect(roles).toEqual(currentRoles);
@@ -57,7 +57,7 @@ describe('Auth', () => {
expect(config.cacheController.role.get.calls.count()).toEqual(1); expect(config.cacheController.role.get.calls.count()).toEqual(1);
expect(loadRolesSpy.calls.count()).toEqual(1); expect(loadRolesSpy.calls.count()).toEqual(1);
var firstGet = config.cacheController.role.get.calls.first(); const firstGet = config.cacheController.role.get.calls.first();
expect(firstGet.args[0]).toEqual(currentUserId); expect(firstGet.args[0]).toEqual(currentUserId);
expect(roles).toEqual(currentRoles); expect(roles).toEqual(currentRoles);
done(); done();
@@ -79,8 +79,8 @@ describe('Auth', () => {
}); });
it('should properly handle bcrypt upgrade', (done) => { it('should properly handle bcrypt upgrade', (done) => {
var bcryptOriginal = require('bcrypt-nodejs'); const bcryptOriginal = require('bcrypt-nodejs');
var bcryptNew = require('bcryptjs'); const bcryptNew = require('bcryptjs');
bcryptOriginal.hash('my1Long:password', null, null, function(err, res) { bcryptOriginal.hash('my1Long:password', null, null, function(err, res) {
bcryptNew.compare('my1Long:password', res, function(err, res) { bcryptNew.compare('my1Long:password', res, function(err, res) {
expect(res).toBeTruthy(); expect(res).toBeTruthy();

View File

@@ -1,13 +1,13 @@
var request = require('request'); const request = require('request');
var Config = require("../src/Config"); const Config = require("../src/Config");
var defaultColumns = require('../src/Controllers/SchemaController').defaultColumns; const defaultColumns = require('../src/Controllers/SchemaController').defaultColumns;
var authenticationLoader = require('../src/Adapters/Auth'); const authenticationLoader = require('../src/Adapters/Auth');
var path = require('path'); const path = require('path');
describe('AuthenticationProviders', function() { describe('AuthenticationProviders', function() {
["facebook", "github", "instagram", "google", "linkedin", "meetup", "twitter", "janrainengage", "janraincapture", "vkontakte"].map(function(providerName){ ["facebook", "github", "instagram", "google", "linkedin", "meetup", "twitter", "janrainengage", "janraincapture", "vkontakte"].map(function(providerName){
it("Should validate structure of " + providerName, (done) => { it("Should validate structure of " + providerName, (done) => {
var provider = require("../src/Adapters/Auth/" + providerName); const provider = require("../src/Adapters/Auth/" + providerName);
jequal(typeof provider.validateAuthData, "function"); jequal(typeof provider.validateAuthData, "function");
jequal(typeof provider.validateAppId, "function"); jequal(typeof provider.validateAppId, "function");
const authDataPromise = provider.validateAuthData({}, {}); const authDataPromise = provider.validateAuthData({}, {});
@@ -20,7 +20,7 @@ describe('AuthenticationProviders', function() {
}); });
}); });
var getMockMyOauthProvider = function() { const getMockMyOauthProvider = function() {
return { return {
authData: { authData: {
id: "12345", id: "12345",
@@ -70,18 +70,18 @@ describe('AuthenticationProviders', function() {
} }
}); });
var createOAuthUser = function(callback) { const createOAuthUser = function(callback) {
return createOAuthUserWithSessionToken(undefined, callback); return createOAuthUserWithSessionToken(undefined, callback);
} }
var createOAuthUserWithSessionToken = function(token, callback) { const createOAuthUserWithSessionToken = function(token, callback) {
var jsonBody = { const jsonBody = {
authData: { authData: {
myoauth: getMockMyOauthProvider().authData myoauth: getMockMyOauthProvider().authData
} }
}; };
var options = { const options = {
headers: {'X-Parse-Application-Id': 'test', headers: {'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest', 'X-Parse-REST-API-Key': 'rest',
'X-Parse-Installation-Id': 'yolo', 'X-Parse-Installation-Id': 'yolo',
@@ -105,12 +105,12 @@ describe('AuthenticationProviders', function() {
it("should create user with REST API", done => { it("should create user with REST API", done => {
createOAuthUser((error, response, body) => { createOAuthUser((error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = body; const b = body;
ok(b.sessionToken); ok(b.sessionToken);
expect(b.objectId).not.toBeNull(); expect(b.objectId).not.toBeNull();
expect(b.objectId).not.toBeUndefined(); expect(b.objectId).not.toBeUndefined();
var sessionToken = b.sessionToken; const sessionToken = b.sessionToken;
var q = new Parse.Query("_Session"); const q = new Parse.Query("_Session");
q.equalTo('sessionToken', sessionToken); q.equalTo('sessionToken', sessionToken);
q.first({useMasterKey: true}).then((res) => { q.first({useMasterKey: true}).then((res) => {
if (!res) { if (!res) {
@@ -128,17 +128,17 @@ describe('AuthenticationProviders', function() {
}); });
it("should only create a single user with REST API", (done) => { it("should only create a single user with REST API", (done) => {
var objectId; let objectId;
createOAuthUser((error, response, body) => { createOAuthUser((error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = body const b = body
expect(b.objectId).not.toBeNull(); expect(b.objectId).not.toBeNull();
expect(b.objectId).not.toBeUndefined(); expect(b.objectId).not.toBeUndefined();
objectId = b.objectId; objectId = b.objectId;
createOAuthUser((error, response, body) => { createOAuthUser((error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = body; const b = body;
expect(b.objectId).not.toBeNull(); expect(b.objectId).not.toBeNull();
expect(b.objectId).not.toBeUndefined(); expect(b.objectId).not.toBeUndefined();
expect(b.objectId).toBe(objectId); expect(b.objectId).toBe(objectId);
@@ -164,7 +164,7 @@ describe('AuthenticationProviders', function() {
}); });
it("unlink and link with custom provider", (done) => { it("unlink and link with custom provider", (done) => {
var provider = getMockMyOauthProvider(); const provider = getMockMyOauthProvider();
Parse.User._registerAuthenticationProvider(provider); Parse.User._registerAuthenticationProvider(provider);
Parse.User._logInWith("myoauth", { Parse.User._logInWith("myoauth", {
success: function(model) { success: function(model) {
@@ -186,7 +186,7 @@ describe('AuthenticationProviders', function() {
ok(!provider.synchronizedExpiration, ok(!provider.synchronizedExpiration,
"Expiration should be cleared"); "Expiration should be cleared");
// make sure the auth data is properly deleted // make sure the auth data is properly deleted
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
config.database.adapter.find('_User', { config.database.adapter.find('_User', {
fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation), fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation),
}, { objectId: model.id }, {}) }, { objectId: model.id }, {})
@@ -244,7 +244,7 @@ describe('AuthenticationProviders', function() {
} }
it('properly loads custom adapter', (done) => { it('properly loads custom adapter', (done) => {
var validAuthData = { const validAuthData = {
id: 'hello', id: 'hello',
token: 'world' token: 'world'
} }

View File

@@ -3,7 +3,7 @@ import commander from '../src/cli/utils/commander';
import definitions from '../src/cli/definitions/parse-server'; import definitions from '../src/cli/definitions/parse-server';
import liveQueryDefinitions from '../src/cli/definitions/parse-live-query-server'; import liveQueryDefinitions from '../src/cli/definitions/parse-live-query-server';
var testDefinitions = { const testDefinitions = {
'arg0': 'PROGRAM_ARG_0', 'arg0': 'PROGRAM_ARG_0',
'arg1': { 'arg1': {
env: 'PROGRAM_ARG_1', env: 'PROGRAM_ARG_1',
@@ -12,7 +12,7 @@ var testDefinitions = {
'arg2': { 'arg2': {
env: 'PROGRAM_ARG_2', env: 'PROGRAM_ARG_2',
action: function(value) { action: function(value) {
var intValue = parseInt(value); const intValue = parseInt(value);
if (!Number.isInteger(intValue)) { if (!Number.isInteger(intValue)) {
throw 'arg2 is invalid'; throw 'arg2 is invalid';
} }

View File

@@ -1,9 +1,9 @@
var CacheController = require('../src/Controllers/CacheController.js').default; const CacheController = require('../src/Controllers/CacheController.js').default;
describe('CacheController', function() { describe('CacheController', function() {
var FakeCacheAdapter; let FakeCacheAdapter;
var FakeAppID = 'foo'; const FakeAppID = 'foo';
var KEY = 'hello'; const KEY = 'hello';
beforeEach(() => { beforeEach(() => {
FakeCacheAdapter = { FakeCacheAdapter = {
@@ -18,7 +18,7 @@ describe('CacheController', function() {
it('should expose role and user caches', (done) => { it('should expose role and user caches', (done) => {
var cache = new CacheController(FakeCacheAdapter, FakeAppID); const cache = new CacheController(FakeCacheAdapter, FakeAppID);
expect(cache.role).not.toEqual(null); expect(cache.role).not.toEqual(null);
expect(cache.role.get).not.toEqual(null); expect(cache.role.get).not.toEqual(null);
@@ -31,24 +31,24 @@ describe('CacheController', function() {
['role', 'user'].forEach((cacheName) => { ['role', 'user'].forEach((cacheName) => {
it('should prefix ' + cacheName + ' cache', () => { it('should prefix ' + cacheName + ' cache', () => {
var cache = new CacheController(FakeCacheAdapter, FakeAppID)[cacheName]; const cache = new CacheController(FakeCacheAdapter, FakeAppID)[cacheName];
cache.put(KEY, 'world'); cache.put(KEY, 'world');
var firstPut = FakeCacheAdapter.put.calls.first(); const firstPut = FakeCacheAdapter.put.calls.first();
expect(firstPut.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':')); expect(firstPut.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':'));
cache.get(KEY); cache.get(KEY);
var firstGet = FakeCacheAdapter.get.calls.first(); const firstGet = FakeCacheAdapter.get.calls.first();
expect(firstGet.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':')); expect(firstGet.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':'));
cache.del(KEY); cache.del(KEY);
var firstDel = FakeCacheAdapter.del.calls.first(); const firstDel = FakeCacheAdapter.del.calls.first();
expect(firstDel.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':')); expect(firstDel.args[0]).toEqual([FakeAppID, cacheName, KEY].join(':'));
}); });
}); });
it('should clear the entire cache', () => { it('should clear the entire cache', () => {
var cache = new CacheController(FakeCacheAdapter, FakeAppID); const cache = new CacheController(FakeCacheAdapter, FakeAppID);
cache.clear(); cache.clear();
expect(FakeCacheAdapter.clear.calls.count()).toEqual(1); expect(FakeCacheAdapter.clear.calls.count()).toEqual(1);
@@ -64,7 +64,7 @@ describe('CacheController', function() {
FakeCacheAdapter.get = () => Promise.reject(); FakeCacheAdapter.get = () => Promise.reject();
var cache = new CacheController(FakeCacheAdapter, FakeAppID); const cache = new CacheController(FakeCacheAdapter, FakeAppID);
cache.get('foo').then(done, () => { cache.get('foo').then(done, () => {
fail('Promise should not be rejected.'); fail('Promise should not be rejected.');

View File

@@ -1,10 +1,10 @@
var Client = require('../src/LiveQuery/Client').Client; const Client = require('../src/LiveQuery/Client').Client;
var ParseWebSocket = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocket; const ParseWebSocket = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocket;
describe('Client', function() { describe('Client', function() {
it('can be initialized', function() { it('can be initialized', function() {
var parseWebSocket = new ParseWebSocket({}); const parseWebSocket = new ParseWebSocket({});
var client = new Client(1, parseWebSocket); const client = new Client(1, parseWebSocket);
expect(client.id).toBe(1); expect(client.id).toBe(1);
expect(client.parseWebSocket).toBe(parseWebSocket); expect(client.parseWebSocket).toBe(parseWebSocket);
@@ -12,7 +12,7 @@ describe('Client', function() {
}); });
it('can push response', function() { it('can push response', function() {
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
Client.pushResponse(parseWebSocket, 'message'); Client.pushResponse(parseWebSocket, 'message');
@@ -21,13 +21,13 @@ describe('Client', function() {
}); });
it('can push error', function() { it('can push error', function() {
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
Client.pushError(parseWebSocket, 1, 'error', true); Client.pushError(parseWebSocket, 1, 'error', true);
var lastCall = parseWebSocket.send.calls.first(); const lastCall = parseWebSocket.send.calls.first();
var messageJSON = JSON.parse(lastCall.args[0]); const messageJSON = JSON.parse(lastCall.args[0]);
expect(messageJSON.op).toBe('error'); expect(messageJSON.op).toBe('error');
expect(messageJSON.error).toBe('error'); expect(messageJSON.error).toBe('error');
expect(messageJSON.code).toBe(1); expect(messageJSON.code).toBe(1);
@@ -35,13 +35,13 @@ describe('Client', function() {
}); });
it('can add subscription information', function() { it('can add subscription information', function() {
var subscription = {}; const subscription = {};
var fields = ['test']; const fields = ['test'];
var subscriptionInfo = { const subscriptionInfo = {
subscription: subscription, subscription: subscription,
fields: fields fields: fields
} }
var client = new Client(1, {}); const client = new Client(1, {});
client.addSubscriptionInfo(1, subscriptionInfo); client.addSubscriptionInfo(1, subscriptionInfo);
expect(client.subscriptionInfos.size).toBe(1); expect(client.subscriptionInfos.size).toBe(1);
@@ -49,27 +49,27 @@ describe('Client', function() {
}); });
it('can get subscription information', function() { it('can get subscription information', function() {
var subscription = {}; const subscription = {};
var fields = ['test']; const fields = ['test'];
var subscriptionInfo = { const subscriptionInfo = {
subscription: subscription, subscription: subscription,
fields: fields fields: fields
} }
var client = new Client(1, {}); const client = new Client(1, {});
client.addSubscriptionInfo(1, subscriptionInfo); client.addSubscriptionInfo(1, subscriptionInfo);
var subscriptionInfoAgain = client.getSubscriptionInfo(1); const subscriptionInfoAgain = client.getSubscriptionInfo(1);
expect(subscriptionInfoAgain).toBe(subscriptionInfo); expect(subscriptionInfoAgain).toBe(subscriptionInfo);
}); });
it('can delete subscription information', function() { it('can delete subscription information', function() {
var subscription = {}; const subscription = {};
var fields = ['test']; const fields = ['test'];
var subscriptionInfo = { const subscriptionInfo = {
subscription: subscription, subscription: subscription,
fields: fields fields: fields
} }
var client = new Client(1, {}); const client = new Client(1, {});
client.addSubscriptionInfo(1, subscriptionInfo); client.addSubscriptionInfo(1, subscriptionInfo);
client.deleteSubscriptionInfo(1); client.deleteSubscriptionInfo(1);
@@ -78,7 +78,7 @@ describe('Client', function() {
it('can generate ParseObject JSON with null selected field', function() { it('can generate ParseObject JSON with null selected field', function() {
var parseObjectJSON = { const parseObjectJSON = {
key : 'value', key : 'value',
className: 'test', className: 'test',
objectId: 'test', objectId: 'test',
@@ -86,13 +86,13 @@ describe('Client', function() {
createdAt: '2015-12-07T21:27:13.746Z', createdAt: '2015-12-07T21:27:13.746Z',
ACL: 'test', ACL: 'test',
}; };
var client = new Client(1, {}); const client = new Client(1, {});
expect(client._toJSONWithFields(parseObjectJSON, null)).toBe(parseObjectJSON); expect(client._toJSONWithFields(parseObjectJSON, null)).toBe(parseObjectJSON);
}); });
it('can generate ParseObject JSON with undefined selected field', function() { it('can generate ParseObject JSON with undefined selected field', function() {
var parseObjectJSON = { const parseObjectJSON = {
key : 'value', key : 'value',
className: 'test', className: 'test',
objectId: 'test', objectId: 'test',
@@ -100,13 +100,13 @@ describe('Client', function() {
createdAt: '2015-12-07T21:27:13.746Z', createdAt: '2015-12-07T21:27:13.746Z',
ACL: 'test', ACL: 'test',
}; };
var client = new Client(1, {}); const client = new Client(1, {});
expect(client._toJSONWithFields(parseObjectJSON, undefined)).toBe(parseObjectJSON); expect(client._toJSONWithFields(parseObjectJSON, undefined)).toBe(parseObjectJSON);
}); });
it('can generate ParseObject JSON with selected fields', function() { it('can generate ParseObject JSON with selected fields', function() {
var parseObjectJSON = { const parseObjectJSON = {
key : 'value', key : 'value',
className: 'test', className: 'test',
objectId: 'test', objectId: 'test',
@@ -115,7 +115,7 @@ describe('Client', function() {
ACL: 'test', ACL: 'test',
test: 'test' test: 'test'
}; };
var client = new Client(1, {}); const client = new Client(1, {});
expect(client._toJSONWithFields(parseObjectJSON, ['test'])).toEqual({ expect(client._toJSONWithFields(parseObjectJSON, ['test'])).toEqual({
className: 'test', className: 'test',
@@ -128,7 +128,7 @@ describe('Client', function() {
}); });
it('can generate ParseObject JSON with nonexistent selected fields', function() { it('can generate ParseObject JSON with nonexistent selected fields', function() {
var parseObjectJSON = { const parseObjectJSON = {
key : 'value', key : 'value',
className: 'test', className: 'test',
objectId: 'test', objectId: 'test',
@@ -137,8 +137,8 @@ describe('Client', function() {
ACL: 'test', ACL: 'test',
test: 'test' test: 'test'
}; };
var client = new Client(1, {}); const client = new Client(1, {});
var limitedParseObject = client._toJSONWithFields(parseObjectJSON, ['name']); const limitedParseObject = client._toJSONWithFields(parseObjectJSON, ['name']);
expect(limitedParseObject).toEqual({ expect(limitedParseObject).toEqual({
className: 'test', className: 'test',
@@ -151,48 +151,48 @@ describe('Client', function() {
}); });
it('can push connect response', function() { it('can push connect response', function() {
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
var client = new Client(1, parseWebSocket); const client = new Client(1, parseWebSocket);
client.pushConnect(); client.pushConnect();
var lastCall = parseWebSocket.send.calls.first(); const lastCall = parseWebSocket.send.calls.first();
var messageJSON = JSON.parse(lastCall.args[0]); const messageJSON = JSON.parse(lastCall.args[0]);
expect(messageJSON.op).toBe('connected'); expect(messageJSON.op).toBe('connected');
expect(messageJSON.clientId).toBe(1); expect(messageJSON.clientId).toBe(1);
}); });
it('can push subscribe response', function() { it('can push subscribe response', function() {
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
var client = new Client(1, parseWebSocket); const client = new Client(1, parseWebSocket);
client.pushSubscribe(2); client.pushSubscribe(2);
var lastCall = parseWebSocket.send.calls.first(); const lastCall = parseWebSocket.send.calls.first();
var messageJSON = JSON.parse(lastCall.args[0]); const messageJSON = JSON.parse(lastCall.args[0]);
expect(messageJSON.op).toBe('subscribed'); expect(messageJSON.op).toBe('subscribed');
expect(messageJSON.clientId).toBe(1); expect(messageJSON.clientId).toBe(1);
expect(messageJSON.requestId).toBe(2); expect(messageJSON.requestId).toBe(2);
}); });
it('can push unsubscribe response', function() { it('can push unsubscribe response', function() {
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
var client = new Client(1, parseWebSocket); const client = new Client(1, parseWebSocket);
client.pushUnsubscribe(2); client.pushUnsubscribe(2);
var lastCall = parseWebSocket.send.calls.first(); const lastCall = parseWebSocket.send.calls.first();
var messageJSON = JSON.parse(lastCall.args[0]); const messageJSON = JSON.parse(lastCall.args[0]);
expect(messageJSON.op).toBe('unsubscribed'); expect(messageJSON.op).toBe('unsubscribed');
expect(messageJSON.clientId).toBe(1); expect(messageJSON.clientId).toBe(1);
expect(messageJSON.requestId).toBe(2); expect(messageJSON.requestId).toBe(2);
}); });
it('can push create response', function() { it('can push create response', function() {
var parseObjectJSON = { const parseObjectJSON = {
key : 'value', key : 'value',
className: 'test', className: 'test',
objectId: 'test', objectId: 'test',
@@ -201,14 +201,14 @@ describe('Client', function() {
ACL: 'test', ACL: 'test',
test: 'test' test: 'test'
}; };
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
var client = new Client(1, parseWebSocket); const client = new Client(1, parseWebSocket);
client.pushCreate(2, parseObjectJSON); client.pushCreate(2, parseObjectJSON);
var lastCall = parseWebSocket.send.calls.first(); const lastCall = parseWebSocket.send.calls.first();
var messageJSON = JSON.parse(lastCall.args[0]); const messageJSON = JSON.parse(lastCall.args[0]);
expect(messageJSON.op).toBe('create'); expect(messageJSON.op).toBe('create');
expect(messageJSON.clientId).toBe(1); expect(messageJSON.clientId).toBe(1);
expect(messageJSON.requestId).toBe(2); expect(messageJSON.requestId).toBe(2);
@@ -216,7 +216,7 @@ describe('Client', function() {
}); });
it('can push enter response', function() { it('can push enter response', function() {
var parseObjectJSON = { const parseObjectJSON = {
key : 'value', key : 'value',
className: 'test', className: 'test',
objectId: 'test', objectId: 'test',
@@ -225,14 +225,14 @@ describe('Client', function() {
ACL: 'test', ACL: 'test',
test: 'test' test: 'test'
}; };
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
var client = new Client(1, parseWebSocket); const client = new Client(1, parseWebSocket);
client.pushEnter(2, parseObjectJSON); client.pushEnter(2, parseObjectJSON);
var lastCall = parseWebSocket.send.calls.first(); const lastCall = parseWebSocket.send.calls.first();
var messageJSON = JSON.parse(lastCall.args[0]); const messageJSON = JSON.parse(lastCall.args[0]);
expect(messageJSON.op).toBe('enter'); expect(messageJSON.op).toBe('enter');
expect(messageJSON.clientId).toBe(1); expect(messageJSON.clientId).toBe(1);
expect(messageJSON.requestId).toBe(2); expect(messageJSON.requestId).toBe(2);
@@ -240,7 +240,7 @@ describe('Client', function() {
}); });
it('can push update response', function() { it('can push update response', function() {
var parseObjectJSON = { const parseObjectJSON = {
key : 'value', key : 'value',
className: 'test', className: 'test',
objectId: 'test', objectId: 'test',
@@ -249,14 +249,14 @@ describe('Client', function() {
ACL: 'test', ACL: 'test',
test: 'test' test: 'test'
}; };
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
var client = new Client(1, parseWebSocket); const client = new Client(1, parseWebSocket);
client.pushUpdate(2, parseObjectJSON); client.pushUpdate(2, parseObjectJSON);
var lastCall = parseWebSocket.send.calls.first(); const lastCall = parseWebSocket.send.calls.first();
var messageJSON = JSON.parse(lastCall.args[0]); const messageJSON = JSON.parse(lastCall.args[0]);
expect(messageJSON.op).toBe('update'); expect(messageJSON.op).toBe('update');
expect(messageJSON.clientId).toBe(1); expect(messageJSON.clientId).toBe(1);
expect(messageJSON.requestId).toBe(2); expect(messageJSON.requestId).toBe(2);
@@ -264,7 +264,7 @@ describe('Client', function() {
}); });
it('can push leave response', function() { it('can push leave response', function() {
var parseObjectJSON = { const parseObjectJSON = {
key : 'value', key : 'value',
className: 'test', className: 'test',
objectId: 'test', objectId: 'test',
@@ -273,14 +273,14 @@ describe('Client', function() {
ACL: 'test', ACL: 'test',
test: 'test' test: 'test'
}; };
var parseWebSocket = { const parseWebSocket = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
var client = new Client(1, parseWebSocket); const client = new Client(1, parseWebSocket);
client.pushLeave(2, parseObjectJSON); client.pushLeave(2, parseObjectJSON);
var lastCall = parseWebSocket.send.calls.first(); const lastCall = parseWebSocket.send.calls.first();
var messageJSON = JSON.parse(lastCall.args[0]); const messageJSON = JSON.parse(lastCall.args[0]);
expect(messageJSON.op).toBe('leave'); expect(messageJSON.op).toBe('leave');
expect(messageJSON.clientId).toBe(1); expect(messageJSON.clientId).toBe(1);
expect(messageJSON.requestId).toBe(2); expect(messageJSON.requestId).toBe(2);

View File

@@ -1,4 +1,4 @@
var ClientSDK = require('../src/ClientSDK'); const ClientSDK = require('../src/ClientSDK');
describe('ClientSDK', () => { describe('ClientSDK', () => {
it('should properly parse the SDK versions', () => { it('should properly parse the SDK versions', () => {

View File

@@ -48,7 +48,7 @@ describe('Cloud Code', () => {
res.error('You shall not pass!'); res.error('You shall not pass!');
}); });
var obj = new Parse.Object('BeforeSaveFail'); const obj = new Parse.Object('BeforeSaveFail');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(() => { obj.save().then(() => {
fail('Should not have been able to save BeforeSaveFailure class.'); fail('Should not have been able to save BeforeSaveFailure class.');
@@ -80,7 +80,7 @@ describe('Cloud Code', () => {
res.error(999, 'Nope'); res.error(999, 'Nope');
}); });
var obj = new Parse.Object('BeforeSaveFailWithErrorCode'); const obj = new Parse.Object('BeforeSaveFailWithErrorCode');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(function() { obj.save().then(function() {
fail('Should not have been able to save BeforeSaveFailWithErrorCode class.'); fail('Should not have been able to save BeforeSaveFailWithErrorCode class.');
@@ -94,7 +94,7 @@ describe('Cloud Code', () => {
it('basic beforeSave rejection via promise', function(done) { it('basic beforeSave rejection via promise', function(done) {
Parse.Cloud.beforeSave('BeforeSaveFailWithPromise', function (req, res) { Parse.Cloud.beforeSave('BeforeSaveFailWithPromise', function (req, res) {
var query = new Parse.Query('Yolo'); const query = new Parse.Query('Yolo');
query.find().then(() => { query.find().then(() => {
res.error('Nope'); res.error('Nope');
}, () => { }, () => {
@@ -102,7 +102,7 @@ describe('Cloud Code', () => {
}); });
}); });
var obj = new Parse.Object('BeforeSaveFailWithPromise'); const obj = new Parse.Object('BeforeSaveFailWithPromise');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(function() { obj.save().then(function() {
fail('Should not have been able to save BeforeSaveFailure class.'); fail('Should not have been able to save BeforeSaveFailure class.');
@@ -120,10 +120,10 @@ describe('Cloud Code', () => {
res.success(); res.success();
}); });
var obj = new Parse.Object('BeforeSaveChanged'); const obj = new Parse.Object('BeforeSaveChanged');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(function() { obj.save().then(function() {
var query = new Parse.Query('BeforeSaveChanged'); const query = new Parse.Query('BeforeSaveChanged');
query.get(obj.id).then(function(objAgain) { query.get(obj.id).then(function(objAgain) {
expect(objAgain.get('foo')).toEqual('baz'); expect(objAgain.get('foo')).toEqual('baz');
done(); done();
@@ -143,7 +143,7 @@ describe('Cloud Code', () => {
res.success(); res.success();
}); });
var obj = new Parse.Object('BeforeSaveChanged'); const obj = new Parse.Object('BeforeSaveChanged');
obj.set('foo', 'bing'); obj.set('foo', 'bing');
obj.save().then(() => { obj.save().then(() => {
expect(obj.get('foo')).toEqual('baz'); expect(obj.get('foo')).toEqual('baz');
@@ -157,16 +157,16 @@ describe('Cloud Code', () => {
it('test afterSave ran and created an object', function(done) { it('test afterSave ran and created an object', function(done) {
Parse.Cloud.afterSave('AfterSaveTest', function(req) { Parse.Cloud.afterSave('AfterSaveTest', function(req) {
var obj = new Parse.Object('AfterSaveProof'); const obj = new Parse.Object('AfterSaveProof');
obj.set('proof', req.object.id); obj.set('proof', req.object.id);
obj.save(); obj.save();
}); });
var obj = new Parse.Object('AfterSaveTest'); const obj = new Parse.Object('AfterSaveTest');
obj.save(); obj.save();
setTimeout(function() { setTimeout(function() {
var query = new Parse.Query('AfterSaveProof'); const query = new Parse.Query('AfterSaveProof');
query.equalTo('proof', obj.id); query.equalTo('proof', obj.id);
query.find().then(function(results) { query.find().then(function(results) {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
@@ -341,13 +341,13 @@ describe('Cloud Code', () => {
res.success(); res.success();
}); });
var obj = new Parse.Object('BeforeSaveChanged'); const obj = new Parse.Object('BeforeSaveChanged');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(function() { obj.save().then(function() {
obj.set('foo', 'bar'); obj.set('foo', 'bar');
return obj.save(); return obj.save();
}).then(function() { }).then(function() {
var query = new Parse.Query('BeforeSaveChanged'); const query = new Parse.Query('BeforeSaveChanged');
return query.get(obj.id).then(function(objAgain) { return query.get(obj.id).then(function(objAgain) {
expect(objAgain.get('foo')).toEqual('baz'); expect(objAgain.get('foo')).toEqual('baz');
done(); done();
@@ -363,8 +363,8 @@ describe('Cloud Code', () => {
res.error('Nope'); res.error('Nope');
}); });
var obj = new Parse.Object('BeforeDeleteFail'); const obj = new Parse.Object('BeforeDeleteFail');
var id; let id;
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(() => { obj.save().then(() => {
id = obj.id; id = obj.id;
@@ -376,7 +376,7 @@ describe('Cloud Code', () => {
expect(error.code).toEqual(Parse.Error.SCRIPT_FAILED); expect(error.code).toEqual(Parse.Error.SCRIPT_FAILED);
expect(error.message).toEqual('Nope'); expect(error.message).toEqual('Nope');
var objAgain = new Parse.Object('BeforeDeleteFail', {objectId: id}); const objAgain = new Parse.Object('BeforeDeleteFail', {objectId: id});
return objAgain.fetch(); return objAgain.fetch();
}).then((objAgain) => { }).then((objAgain) => {
if (objAgain) { if (objAgain) {
@@ -393,7 +393,7 @@ describe('Cloud Code', () => {
it('basic beforeDelete rejection via promise', function(done) { it('basic beforeDelete rejection via promise', function(done) {
Parse.Cloud.beforeSave('BeforeDeleteFailWithPromise', function (req, res) { Parse.Cloud.beforeSave('BeforeDeleteFailWithPromise', function (req, res) {
var query = new Parse.Query('Yolo'); const query = new Parse.Query('Yolo');
query.find().then(() => { query.find().then(() => {
res.error('Nope'); res.error('Nope');
}, () => { }, () => {
@@ -401,7 +401,7 @@ describe('Cloud Code', () => {
}); });
}); });
var obj = new Parse.Object('BeforeDeleteFailWithPromise'); const obj = new Parse.Object('BeforeDeleteFailWithPromise');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(function() { obj.save().then(function() {
fail('Should not have been able to save BeforeSaveFailure class.'); fail('Should not have been able to save BeforeSaveFailure class.');
@@ -416,18 +416,18 @@ describe('Cloud Code', () => {
it('test afterDelete ran and created an object', function(done) { it('test afterDelete ran and created an object', function(done) {
Parse.Cloud.afterDelete('AfterDeleteTest', function(req) { Parse.Cloud.afterDelete('AfterDeleteTest', function(req) {
var obj = new Parse.Object('AfterDeleteProof'); const obj = new Parse.Object('AfterDeleteProof');
obj.set('proof', req.object.id); obj.set('proof', req.object.id);
obj.save(); obj.save();
}); });
var obj = new Parse.Object('AfterDeleteTest'); const obj = new Parse.Object('AfterDeleteTest');
obj.save().then(function() { obj.save().then(function() {
obj.destroy(); obj.destroy();
}); });
setTimeout(function() { setTimeout(function() {
var query = new Parse.Query('AfterDeleteProof'); const query = new Parse.Query('AfterDeleteProof');
query.equalTo('proof', obj.id); query.equalTo('proof', obj.id);
query.find().then(function(results) { query.find().then(function(results) {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
@@ -473,7 +473,7 @@ describe('Cloud Code', () => {
} }
expect(result.object.className).toEqual('Foo'); expect(result.object.className).toEqual('Foo');
expect(result.object.get('x')).toEqual(2); expect(result.object.get('x')).toEqual(2);
var bar = result.object.get('relation'); const bar = result.object.get('relation');
expect(bar instanceof Parse.Object).toBeTruthy(); expect(bar instanceof Parse.Object).toBeTruthy();
expect(bar.className).toEqual('Bar'); expect(bar.className).toEqual('Bar');
expect(bar.get('x')).toEqual(3); expect(bar.get('x')).toEqual(3);
@@ -582,7 +582,7 @@ describe('Cloud Code', () => {
}); });
Parse.Cloud.define('createBeforeSaveChangedObject', function(req, res){ Parse.Cloud.define('createBeforeSaveChangedObject', function(req, res){
var obj = new Parse.Object('BeforeSaveChanged'); const obj = new Parse.Object('BeforeSaveChanged');
obj.save().then(() => { obj.save().then(() => {
res.success(obj); res.success(obj);
}) })
@@ -598,7 +598,7 @@ describe('Cloud Code', () => {
let triggerTime = 0; let triggerTime = 0;
// Register a mock beforeSave hook // Register a mock beforeSave hook
Parse.Cloud.beforeSave('GameScore', (req, res) => { Parse.Cloud.beforeSave('GameScore', (req, res) => {
var object = req.object; const object = req.object;
expect(object instanceof Parse.Object).toBeTruthy(); expect(object instanceof Parse.Object).toBeTruthy();
expect(object.get('fooAgain')).toEqual('barAgain'); expect(object.get('fooAgain')).toEqual('barAgain');
if (triggerTime == 0) { if (triggerTime == 0) {
@@ -638,7 +638,7 @@ describe('Cloud Code', () => {
res.success(); res.success();
}); });
var obj = new Parse.Object('BeforeSaveUnchanged'); const obj = new Parse.Object('BeforeSaveUnchanged');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(function() { obj.save().then(function() {
done(); done();
@@ -653,12 +653,12 @@ describe('Cloud Code', () => {
res.success(); res.success();
}); });
var obj = new Parse.Object('BeforeDeleteTest'); const obj = new Parse.Object('BeforeDeleteTest');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(function() { obj.save().then(function() {
return obj.destroy(); return obj.destroy();
}).then(function() { }).then(function() {
var objAgain = new Parse.Object('BeforeDeleteTest', obj.id); const objAgain = new Parse.Object('BeforeDeleteTest', obj.id);
return objAgain.fetch().then(fail, done); return objAgain.fetch().then(fail, done);
}, function(error) { }, function(error) {
fail(error); fail(error);
@@ -681,13 +681,13 @@ describe('Cloud Code', () => {
} }
}); });
var user = new Parse.User(); const user = new Parse.User();
user.set("password", "asdf"); user.set("password", "asdf");
user.set("email", "asdf@example.com"); user.set("email", "asdf@example.com");
user.set("username", "zxcv"); user.set("username", "zxcv");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var obj = new Parse.Object('SaveTriggerUser'); const obj = new Parse.Object('SaveTriggerUser');
obj.save().then(function() { obj.save().then(function() {
done(); done();
}, function(error) { }, function(error) {
@@ -855,15 +855,15 @@ describe('Cloud Code', () => {
res.success(); res.success();
}); });
var TestObject = Parse.Object.extend("TestObject"); const TestObject = Parse.Object.extend("TestObject");
var NoBeforeSaveObject = Parse.Object.extend("NoBeforeSave"); const NoBeforeSaveObject = Parse.Object.extend("NoBeforeSave");
var BeforeSaveObject = Parse.Object.extend("BeforeSaveUnchanged"); const BeforeSaveObject = Parse.Object.extend("BeforeSaveUnchanged");
var aTestObject = new TestObject(); const aTestObject = new TestObject();
aTestObject.set("foo", "bar"); aTestObject.set("foo", "bar");
aTestObject.save() aTestObject.save()
.then(aTestObject => { .then(aTestObject => {
var aNoBeforeSaveObj = new NoBeforeSaveObject(); const aNoBeforeSaveObj = new NoBeforeSaveObject();
aNoBeforeSaveObj.set("aTestObject", aTestObject); aNoBeforeSaveObj.set("aTestObject", aTestObject);
expect(aNoBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar"); expect(aNoBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar");
return aNoBeforeSaveObj.save(); return aNoBeforeSaveObj.save();
@@ -871,7 +871,7 @@ describe('Cloud Code', () => {
.then(aNoBeforeSaveObj => { .then(aNoBeforeSaveObj => {
expect(aNoBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar"); expect(aNoBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar");
var aBeforeSaveObj = new BeforeSaveObject(); const aBeforeSaveObj = new BeforeSaveObject();
aBeforeSaveObj.set("aTestObject", aTestObject); aBeforeSaveObj.set("aTestObject", aTestObject);
expect(aBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar"); expect(aBeforeSaveObj.get("aTestObject").get("foo")).toEqual("bar");
return aBeforeSaveObj.save(); return aBeforeSaveObj.save();
@@ -892,15 +892,15 @@ describe('Cloud Code', () => {
res.success(); res.success();
}); });
var TestObject = Parse.Object.extend("TestObject"); const TestObject = Parse.Object.extend("TestObject");
var BeforeSaveUnchangedObject = Parse.Object.extend("BeforeSaveUnchanged"); const BeforeSaveUnchangedObject = Parse.Object.extend("BeforeSaveUnchanged");
var BeforeSaveChangedObject = Parse.Object.extend("BeforeSaveChanged"); const BeforeSaveChangedObject = Parse.Object.extend("BeforeSaveChanged");
var aTestObject = new TestObject(); const aTestObject = new TestObject();
aTestObject.set("foo", "bar"); aTestObject.set("foo", "bar");
aTestObject.save() aTestObject.save()
.then(aTestObject => { .then(aTestObject => {
var aBeforeSaveUnchangedObject = new BeforeSaveUnchangedObject(); const aBeforeSaveUnchangedObject = new BeforeSaveUnchangedObject();
aBeforeSaveUnchangedObject.set("aTestObject", aTestObject); aBeforeSaveUnchangedObject.set("aTestObject", aTestObject);
expect(aBeforeSaveUnchangedObject.get("aTestObject").get("foo")).toEqual("bar"); expect(aBeforeSaveUnchangedObject.get("aTestObject").get("foo")).toEqual("bar");
return aBeforeSaveUnchangedObject.save(); return aBeforeSaveUnchangedObject.save();
@@ -908,7 +908,7 @@ describe('Cloud Code', () => {
.then(aBeforeSaveUnchangedObject => { .then(aBeforeSaveUnchangedObject => {
expect(aBeforeSaveUnchangedObject.get("aTestObject").get("foo")).toEqual("bar"); expect(aBeforeSaveUnchangedObject.get("aTestObject").get("foo")).toEqual("bar");
var aBeforeSaveChangedObject = new BeforeSaveChangedObject(); const aBeforeSaveChangedObject = new BeforeSaveChangedObject();
aBeforeSaveChangedObject.set("aTestObject", aTestObject); aBeforeSaveChangedObject.set("aTestObject", aTestObject);
expect(aBeforeSaveChangedObject.get("aTestObject").get("foo")).toEqual("bar"); expect(aBeforeSaveChangedObject.get("aTestObject").get("foo")).toEqual("bar");
return aBeforeSaveChangedObject.save(); return aBeforeSaveChangedObject.save();
@@ -921,21 +921,21 @@ describe('Cloud Code', () => {
}); });
it('should fully delete objects when using `unset` with beforeSave (regression test for #1840)', done => { it('should fully delete objects when using `unset` with beforeSave (regression test for #1840)', done => {
var TestObject = Parse.Object.extend('TestObject'); const TestObject = Parse.Object.extend('TestObject');
var NoBeforeSaveObject = Parse.Object.extend('NoBeforeSave'); const NoBeforeSaveObject = Parse.Object.extend('NoBeforeSave');
var BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); const BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged');
Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => { Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => {
var object = req.object; const object = req.object;
object.set('before', 'save'); object.set('before', 'save');
res.success(); res.success();
}); });
Parse.Cloud.define('removeme', (req, res) => { Parse.Cloud.define('removeme', (req, res) => {
var testObject = new TestObject(); const testObject = new TestObject();
testObject.save() testObject.save()
.then(testObject => { .then(testObject => {
var object = new NoBeforeSaveObject({remove: testObject}); const object = new NoBeforeSaveObject({remove: testObject});
return object.save(); return object.save();
}) })
.then(object => { .then(object => {
@@ -948,10 +948,10 @@ describe('Cloud Code', () => {
}); });
Parse.Cloud.define('removeme2', (req, res) => { Parse.Cloud.define('removeme2', (req, res) => {
var testObject = new TestObject(); const testObject = new TestObject();
testObject.save() testObject.save()
.then(testObject => { .then(testObject => {
var object = new BeforeSaveObject({remove: testObject}); const object = new BeforeSaveObject({remove: testObject});
return object.save(); return object.save();
}) })
.then(object => { .then(object => {
@@ -984,11 +984,11 @@ describe('Cloud Code', () => {
trying to delete a field that doesn't exists doesn't play nice trying to delete a field that doesn't exists doesn't play nice
*/ */
it_exclude_dbs(['postgres'])('should fully delete objects when using `unset` with beforeSave (regression test for #1840)', done => { it_exclude_dbs(['postgres'])('should fully delete objects when using `unset` with beforeSave (regression test for #1840)', done => {
var TestObject = Parse.Object.extend('TestObject'); const TestObject = Parse.Object.extend('TestObject');
var BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); const BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged');
Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => { Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => {
var object = req.object; const object = req.object;
object.set('before', 'save'); object.set('before', 'save');
object.unset('remove'); object.unset('remove');
res.success(); res.success();
@@ -1013,11 +1013,11 @@ describe('Cloud Code', () => {
}); });
it('should not include relation op (regression test for #1606)', done => { it('should not include relation op (regression test for #1606)', done => {
var TestObject = Parse.Object.extend('TestObject'); const TestObject = Parse.Object.extend('TestObject');
var BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged'); const BeforeSaveObject = Parse.Object.extend('BeforeSaveChanged');
let testObj; let testObj;
Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => { Parse.Cloud.beforeSave('BeforeSaveChanged', (req, res) => {
var object = req.object; const object = req.object;
object.set('before', 'save'); object.set('before', 'save');
testObj = new TestObject(); testObj = new TestObject();
testObj.save().then(() => { testObj.save().then(() => {

View File

@@ -24,7 +24,7 @@ describe("Cloud Code Logger", () => {
// see helpers.js:afterEach // see helpers.js:afterEach
it("should expose log to functions", done => { it("should expose log to functions", done => {
var logController = new LoggerController(new WinstonLoggerAdapter()); const logController = new LoggerController(new WinstonLoggerAdapter());
Parse.Cloud.define("loggerTest", (req, res) => { Parse.Cloud.define("loggerTest", (req, res) => {
req.log.info('logTest', 'info log', { info: 'some log' }); req.log.info('logTest', 'info log', { info: 'some log' });
@@ -73,7 +73,7 @@ describe("Cloud Code Logger", () => {
}); });
it("should expose log to trigger", (done) => { it("should expose log to trigger", (done) => {
var logController = new LoggerController(new WinstonLoggerAdapter()); const logController = new LoggerController(new WinstonLoggerAdapter());
Parse.Cloud.beforeSave("MyObject", (req, res) => { Parse.Cloud.beforeSave("MyObject", (req, res) => {
req.log.info('beforeSave MyObject', 'info log', { info: 'some log' }); req.log.info('beforeSave MyObject', 'info log', { info: 'some log' });

View File

@@ -1,12 +1,12 @@
var DatabaseController = require('../src/Controllers/DatabaseController.js'); const DatabaseController = require('../src/Controllers/DatabaseController.js');
var validateQuery = DatabaseController._validateQuery; const validateQuery = DatabaseController._validateQuery;
describe('DatabaseController', function() { describe('DatabaseController', function() {
describe('validateQuery', function() { describe('validateQuery', function() {
it('should restructure simple cases of SERVER-13732', (done) => { it('should restructure simple cases of SERVER-13732', (done) => {
var query = {$or: [{a: 1}, {a: 2}], _rperm: {$in: ['a', 'b']}, foo: 3}; const query = {$or: [{a: 1}, {a: 2}], _rperm: {$in: ['a', 'b']}, foo: 3};
validateQuery(query); validateQuery(query);
expect(query).toEqual({$or: [{a: 1, _rperm: {$in: ['a', 'b']}, foo: 3}, expect(query).toEqual({$or: [{a: 1, _rperm: {$in: ['a', 'b']}, foo: 3},
{a: 2, _rperm: {$in: ['a', 'b']}, foo: 3}]}); {a: 2, _rperm: {$in: ['a', 'b']}, foo: 3}]});
@@ -14,7 +14,7 @@ describe('DatabaseController', function() {
}); });
it('should not restructure SERVER-13732 queries with $nears', (done) => { it('should not restructure SERVER-13732 queries with $nears', (done) => {
var query = {$or: [{a: 1}, {b: 1}], c: {$nearSphere: {}}}; let query = {$or: [{a: 1}, {b: 1}], c: {$nearSphere: {}}};
validateQuery(query); validateQuery(query);
expect(query).toEqual({$or: [{a: 1}, {b: 1}], c: {$nearSphere: {}}}); expect(query).toEqual({$or: [{a: 1}, {b: 1}], c: {$nearSphere: {}}});
@@ -27,7 +27,7 @@ describe('DatabaseController', function() {
it('should push refactored keys down a tree for SERVER-13732', (done) => { it('should push refactored keys down a tree for SERVER-13732', (done) => {
var query = {a: 1, $or: [{$or: [{b: 1}, {b: 2}]}, const query = {a: 1, $or: [{$or: [{b: 1}, {b: 2}]},
{$or: [{c: 1}, {c: 2}]}]}; {$or: [{c: 1}, {c: 2}]}]};
validateQuery(query); validateQuery(query);
expect(query).toEqual({$or: [{$or: [{b: 1, a: 1}, {b: 2, a: 1}]}, expect(query).toEqual({$or: [{$or: [{b: 1, a: 1}, {b: 2, a: 1}]},

View File

@@ -7,9 +7,9 @@ const Config = require('../src/Config');
describe("Email Verification Token Expiration: ", () => { describe("Email Verification Token Expiration: ", () => {
it('show the invalid verification link page, if the user clicks on the verify email link after the email verify token expires', done => { it('show the invalid verification link page, if the user clicks on the verify email link after the email verify token expires', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -48,9 +48,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('emailVerified should set to false, if the user does not verify their email before the email verify token expires', done => { it('emailVerified should set to false, if the user does not verify their email before the email verify token expires', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -96,9 +96,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('if user clicks on the email verify link before email verification token expiration then show the verify email success page', done => { it('if user clicks on the email verify link before email verification token expiration then show the verify email success page', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -132,9 +132,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('if user clicks on the email verify link before email verification token expiration then emailVerified should be true', done => { it('if user clicks on the email verify link before email verification token expiration then emailVerified should be true', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -175,9 +175,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('if user clicks on the email verify link before email verification token expiration then user should be able to login', done => { it('if user clicks on the email verify link before email verification token expiration then user should be able to login', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -219,9 +219,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('sets the _email_verify_token_expires_at and _email_verify_token fields after user SignUp', done => { it('sets the _email_verify_token_expires_at and _email_verify_token fields after user SignUp', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -262,9 +262,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('unsets the _email_verify_token_expires_at and _email_verify_token fields in the User class if email verification is successful', done => { it('unsets the _email_verify_token_expires_at and _email_verify_token fields in the User class if email verification is successful', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -314,16 +314,16 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('clicking on the email verify link by an email VERIFIED user that was setup before enabling the expire email verify token should show email verify email success', done => { it('clicking on the email verify link by an email VERIFIED user that was setup before enabling the expire email verify token should show email verify email success', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
sendPasswordResetEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(),
sendMail: () => {} sendMail: () => {}
} }
var serverConfig = { const serverConfig = {
appName: 'emailVerifyToken', appName: 'emailVerifyToken',
verifyUserEmails: true, verifyUserEmails: true,
emailAdapter: emailAdapter, emailAdapter: emailAdapter,
@@ -370,16 +370,16 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('clicking on the email verify link by an email UNVERIFIED user that was setup before enabling the expire email verify token should show invalid verficiation link page', done => { it('clicking on the email verify link by an email UNVERIFIED user that was setup before enabling the expire email verify token should show invalid verficiation link page', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
sendPasswordResetEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(),
sendMail: () => {} sendMail: () => {}
} }
var serverConfig = { const serverConfig = {
appName: 'emailVerifyToken', appName: 'emailVerifyToken',
verifyUserEmails: true, verifyUserEmails: true,
emailAdapter: emailAdapter, emailAdapter: emailAdapter,
@@ -484,11 +484,11 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('should send a new verification email when a resend is requested and the user is UNVERIFIED', done => { it('should send a new verification email when a resend is requested and the user is UNVERIFIED', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var sendVerificationEmailCallCount = 0; let sendVerificationEmailCallCount = 0;
let userBeforeRequest; let userBeforeRequest;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
sendVerificationEmailCallCount++; sendVerificationEmailCallCount++;
@@ -560,10 +560,10 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('should not send a new verification email when a resend is requested and the user is VERIFIED', done => { it('should not send a new verification email when a resend is requested and the user is VERIFIED', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var sendVerificationEmailCallCount = 0; let sendVerificationEmailCallCount = 0;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
sendVerificationEmailCallCount++; sendVerificationEmailCallCount++;
@@ -624,9 +624,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('should not send a new verification email if this user does not exist', done => { it('should not send a new verification email if this user does not exist', done => {
var sendEmailOptions; let sendEmailOptions;
var sendVerificationEmailCallCount = 0; let sendVerificationEmailCallCount = 0;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
sendVerificationEmailCallCount++; sendVerificationEmailCallCount++;
@@ -669,9 +669,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('should fail if no email is supplied', done => { it('should fail if no email is supplied', done => {
var sendEmailOptions; let sendEmailOptions;
var sendVerificationEmailCallCount = 0; let sendVerificationEmailCallCount = 0;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
sendVerificationEmailCallCount++; sendVerificationEmailCallCount++;
@@ -713,9 +713,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('should fail if email is not a string', done => { it('should fail if email is not a string', done => {
var sendEmailOptions; let sendEmailOptions;
var sendVerificationEmailCallCount = 0; let sendVerificationEmailCallCount = 0;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
sendVerificationEmailCallCount++; sendVerificationEmailCallCount++;
@@ -757,9 +757,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('client should not see the _email_verify_token_expires_at field', done => { it('client should not see the _email_verify_token_expires_at field', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -800,9 +800,9 @@ describe("Email Verification Token Expiration: ", () => {
}); });
it('emailVerified should be set to false after changing from an already verified email', done => { it('emailVerified should be set to false after changing from an already verified email', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },

View File

@@ -1,12 +1,12 @@
var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub;
describe('EventEmitterPubSub', function() { describe('EventEmitterPubSub', function() {
it('can publish and subscribe', function() { it('can publish and subscribe', function() {
var publisher = EventEmitterPubSub.createPublisher(); const publisher = EventEmitterPubSub.createPublisher();
var subscriber = EventEmitterPubSub.createSubscriber(); const subscriber = EventEmitterPubSub.createSubscriber();
subscriber.subscribe('testChannel'); subscriber.subscribe('testChannel');
// Register mock checked for subscriber // Register mock checked for subscriber
var isChecked = false; let isChecked = false;
subscriber.on('message', function(channel, message) { subscriber.on('message', function(channel, message) {
isChecked = true; isChecked = true;
expect(channel).toBe('testChannel'); expect(channel).toBe('testChannel');
@@ -19,12 +19,12 @@ describe('EventEmitterPubSub', function() {
}); });
it('can unsubscribe', function() { it('can unsubscribe', function() {
var publisher = EventEmitterPubSub.createPublisher(); const publisher = EventEmitterPubSub.createPublisher();
var subscriber = EventEmitterPubSub.createSubscriber(); const subscriber = EventEmitterPubSub.createSubscriber();
subscriber.subscribe('testChannel'); subscriber.subscribe('testChannel');
subscriber.unsubscribe('testChannel'); subscriber.unsubscribe('testChannel');
// Register mock checked for subscriber // Register mock checked for subscriber
var isCalled = false; let isCalled = false;
subscriber.on('message', function() { subscriber.on('message', function() {
isCalled = true; isCalled = true;
}); });
@@ -35,7 +35,7 @@ describe('EventEmitterPubSub', function() {
}); });
it('can unsubscribe not subscribing channel', function() { it('can unsubscribe not subscribing channel', function() {
var subscriber = EventEmitterPubSub.createSubscriber(); const subscriber = EventEmitterPubSub.createSubscriber();
// Make sure subscriber does not throw exception // Make sure subscriber does not throw exception
subscriber.unsubscribe('testChannel'); subscriber.unsubscribe('testChannel');

View File

@@ -17,19 +17,19 @@ const mockAdapter = {
describe("FilesController",() =>{ describe("FilesController",() =>{
it("should properly expand objects", (done) => { it("should properly expand objects", (done) => {
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var gridStoreAdapter = new GridStoreAdapter('mongodb://localhost:27017/parse'); const gridStoreAdapter = new GridStoreAdapter('mongodb://localhost:27017/parse');
var filesController = new FilesController(gridStoreAdapter) const filesController = new FilesController(gridStoreAdapter)
var result = filesController.expandFilesInObject(config, function(){}); const result = filesController.expandFilesInObject(config, function(){});
expect(result).toBeUndefined(); expect(result).toBeUndefined();
var fullFile = { const fullFile = {
type: '__type', type: '__type',
url: "http://an.url" url: "http://an.url"
} }
var anObject = { const anObject = {
aFile: fullFile aFile: fullFile
} }
filesController.expandFilesInObject(config, anObject); filesController.expandFilesInObject(config, anObject);

View File

@@ -1,24 +1,24 @@
var MongoClient = require("mongodb").MongoClient; const MongoClient = require("mongodb").MongoClient;
var GridStore = require("mongodb").GridStore; const GridStore = require("mongodb").GridStore;
var GridStoreAdapter = require("../src/Adapters/Files/GridStoreAdapter").GridStoreAdapter; const GridStoreAdapter = require("../src/Adapters/Files/GridStoreAdapter").GridStoreAdapter;
var Config = require("../src/Config"); const Config = require("../src/Config");
var FilesController = require('../src/Controllers/FilesController').default; const FilesController = require('../src/Controllers/FilesController').default;
// Small additional tests to improve overall coverage // Small additional tests to improve overall coverage
describe_only_db('mongo')("GridStoreAdapter",() =>{ describe_only_db('mongo')("GridStoreAdapter",() =>{
it("should properly instanciate the GridStore when deleting a file", (done) => { it("should properly instanciate the GridStore when deleting a file", (done) => {
var databaseURI = 'mongodb://localhost:27017/parse'; const databaseURI = 'mongodb://localhost:27017/parse';
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var gridStoreAdapter = new GridStoreAdapter(databaseURI); const gridStoreAdapter = new GridStoreAdapter(databaseURI);
var filesController = new FilesController(gridStoreAdapter); const filesController = new FilesController(gridStoreAdapter);
// save original unlink before redefinition // save original unlink before redefinition
var originalUnlink = GridStore.prototype.unlink; const originalUnlink = GridStore.prototype.unlink;
var gridStoreMode; let gridStoreMode;
// new unlink method that will capture the mode in which GridStore was opened // new unlink method that will capture the mode in which GridStore was opened
GridStore.prototype.unlink = function() { GridStore.prototype.unlink = function() {

View File

@@ -1,14 +1,14 @@
'use strict'; 'use strict';
var httpRequest = require("../src/cloud-code/httpRequest"), const httpRequest = require("../src/cloud-code/httpRequest"),
HTTPResponse = require('../src/cloud-code/HTTPResponse').default, HTTPResponse = require('../src/cloud-code/HTTPResponse').default,
bodyParser = require('body-parser'), bodyParser = require('body-parser'),
express = require("express"); express = require("express");
var port = 13371; const port = 13371;
var httpRequestServer = "http://localhost:" + port; const httpRequestServer = "http://localhost:" + port;
var app = express(); const app = express();
app.use(bodyParser.json({ 'type': '*/*' })); app.use(bodyParser.json({ 'type': '*/*' }));
app.get("/hello", function(req, res){ app.get("/hello", function(req, res){
res.json({response: "OK"}); res.json({response: "OK"});
@@ -53,7 +53,7 @@ describe("httpRequest", () => {
}); });
it("should do /hello with callback and promises", (done) => { it("should do /hello with callback and promises", (done) => {
var calls = 0; let calls = 0;
httpRequest({ httpRequest({
url: httpRequestServer + "/hello", url: httpRequestServer + "/hello",
success: function() { calls++; }, success: function() { calls++; },
@@ -102,7 +102,7 @@ describe("httpRequest", () => {
}); });
it("should fail on 404", (done) => { it("should fail on 404", (done) => {
var calls = 0; let calls = 0;
httpRequest({ httpRequest({
url: httpRequestServer + "/404", url: httpRequestServer + "/404",
success: function() { success: function() {
@@ -138,7 +138,7 @@ describe("httpRequest", () => {
}) })
it("should post on echo", (done) => { it("should post on echo", (done) => {
var calls = 0; let calls = 0;
httpRequest({ httpRequest({
method: "POST", method: "POST",
url: httpRequestServer + "/echo", url: httpRequestServer + "/echo",
@@ -307,7 +307,7 @@ describe("httpRequest", () => {
const httpResponse = new HTTPResponse({}, new Buffer(json)); const httpResponse = new HTTPResponse({}, new Buffer(json));
const encoded = Parse._encode(httpResponse); const encoded = Parse._encode(httpResponse);
let foundData, foundText, foundBody = false; let foundData, foundText, foundBody = false;
for(var key in encoded) { for(const key in encoded) {
if (key == 'data') { if (key == 'data') {
foundData = true; foundData = true;
} }

View File

@@ -2,16 +2,16 @@ const InMemoryCache = require('../src/Adapters/Cache/InMemoryCache').default;
describe('InMemoryCache', function() { describe('InMemoryCache', function() {
var BASE_TTL = { const BASE_TTL = {
ttl: 100 ttl: 100
}; };
var NO_EXPIRE_TTL = { const NO_EXPIRE_TTL = {
ttl: NaN ttl: NaN
}; };
var KEY = 'hello'; const KEY = 'hello';
var KEY_2 = KEY + '_2'; const KEY_2 = KEY + '_2';
var VALUE = 'world'; const VALUE = 'world';
function wait(sleep) { function wait(sleep) {
@@ -21,11 +21,11 @@ describe('InMemoryCache', function() {
} }
it('should destroy a expire items in the cache', (done) => { it('should destroy a expire items in the cache', (done) => {
var cache = new InMemoryCache(BASE_TTL); const cache = new InMemoryCache(BASE_TTL);
cache.put(KEY, VALUE); cache.put(KEY, VALUE);
var value = cache.get(KEY); let value = cache.get(KEY);
expect(value).toEqual(VALUE); expect(value).toEqual(VALUE);
wait(BASE_TTL.ttl * 2).then(() => { wait(BASE_TTL.ttl * 2).then(() => {
@@ -36,7 +36,7 @@ describe('InMemoryCache', function() {
}); });
it('should delete items', (done) => { it('should delete items', (done) => {
var cache = new InMemoryCache(NO_EXPIRE_TTL); const cache = new InMemoryCache(NO_EXPIRE_TTL);
cache.put(KEY, VALUE); cache.put(KEY, VALUE);
cache.put(KEY_2, VALUE); cache.put(KEY_2, VALUE);
expect(cache.get(KEY)).toEqual(VALUE); expect(cache.get(KEY)).toEqual(VALUE);
@@ -53,7 +53,7 @@ describe('InMemoryCache', function() {
}); });
it('should clear all items', (done) => { it('should clear all items', (done) => {
var cache = new InMemoryCache(NO_EXPIRE_TTL); const cache = new InMemoryCache(NO_EXPIRE_TTL);
cache.put(KEY, VALUE); cache.put(KEY, VALUE);
cache.put(KEY_2, VALUE); cache.put(KEY_2, VALUE);
@@ -67,7 +67,7 @@ describe('InMemoryCache', function() {
}); });
it('should deafult TTL to 5 seconds', () => { it('should deafult TTL to 5 seconds', () => {
var cache = new InMemoryCache({}); const cache = new InMemoryCache({});
expect(cache.ttl).toEqual(5 * 1000); expect(cache.ttl).toEqual(5 * 1000);
}); });

View File

@@ -1,8 +1,8 @@
var InMemoryCacheAdapter = require('../src/Adapters/Cache/InMemoryCacheAdapter').default; const InMemoryCacheAdapter = require('../src/Adapters/Cache/InMemoryCacheAdapter').default;
describe('InMemoryCacheAdapter', function() { describe('InMemoryCacheAdapter', function() {
var KEY = 'hello'; const KEY = 'hello';
var VALUE = 'world'; const VALUE = 'world';
function wait(sleep) { function wait(sleep) {
return new Promise(function(resolve) { return new Promise(function(resolve) {
@@ -11,7 +11,7 @@ describe('InMemoryCacheAdapter', function() {
} }
it('should expose promisifyed methods', (done) => { it('should expose promisifyed methods', (done) => {
var cache = new InMemoryCacheAdapter({ const cache = new InMemoryCacheAdapter({
ttl: NaN ttl: NaN
}); });
@@ -27,7 +27,7 @@ describe('InMemoryCacheAdapter', function() {
}); });
it('should get/set/clear', (done) => { it('should get/set/clear', (done) => {
var cache = new InMemoryCacheAdapter({ const cache = new InMemoryCacheAdapter({
ttl: NaN ttl: NaN
}); });
@@ -41,7 +41,7 @@ describe('InMemoryCacheAdapter', function() {
}); });
it('should expire after ttl', (done) => { it('should expire after ttl', (done) => {
var cache = new InMemoryCacheAdapter({ const cache = new InMemoryCacheAdapter({
ttl: 10 ttl: 10
}); });

View File

@@ -1,20 +1,20 @@
var auth = require('../src/Auth'); const auth = require('../src/Auth');
var Config = require('../src/Config'); const Config = require('../src/Config');
var rest = require('../src/rest'); const rest = require('../src/rest');
var InstallationsRouter = require('../src/Routers/InstallationsRouter').InstallationsRouter; const InstallationsRouter = require('../src/Routers/InstallationsRouter').InstallationsRouter;
describe('InstallationsRouter', () => { describe('InstallationsRouter', () => {
it('uses find condition from request.body', (done) => { it('uses find condition from request.body', (done) => {
var config = Config.get('test'); const config = Config.get('test');
var androidDeviceRequest = { const androidDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'installationId': '12345678-abcd-abcd-abcd-123456789abc',
'deviceType': 'android' 'deviceType': 'android'
}; };
var iosDeviceRequest = { const iosDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'installationId': '12345678-abcd-abcd-abcd-123456789abd',
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: { body: {
@@ -26,14 +26,14 @@ describe('InstallationsRouter', () => {
info: {} info: {}
}; };
var router = new InstallationsRouter(); const router = new InstallationsRouter();
rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest)
.then(() => { .then(() => {
return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest);
}).then(() => { }).then(() => {
return router.handleFind(request); return router.handleFind(request);
}).then((res) => { }).then((res) => {
var results = res.response.results; const results = res.response.results;
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
done(); done();
}).catch((err) => { }).catch((err) => {
@@ -43,16 +43,16 @@ describe('InstallationsRouter', () => {
}); });
it('uses find condition from request.query', (done) => { it('uses find condition from request.query', (done) => {
var config = Config.get('test'); const config = Config.get('test');
var androidDeviceRequest = { const androidDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'installationId': '12345678-abcd-abcd-abcd-123456789abc',
'deviceType': 'android' 'deviceType': 'android'
}; };
var iosDeviceRequest = { const iosDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'installationId': '12345678-abcd-abcd-abcd-123456789abd',
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: {}, body: {},
@@ -64,14 +64,14 @@ describe('InstallationsRouter', () => {
info: {} info: {}
}; };
var router = new InstallationsRouter(); const router = new InstallationsRouter();
rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest)
.then(() => { .then(() => {
return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest);
}).then(() => { }).then(() => {
return router.handleFind(request); return router.handleFind(request);
}).then((res) => { }).then((res) => {
var results = res.response.results; const results = res.response.results;
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
done(); done();
}).catch((err) => { }).catch((err) => {
@@ -81,16 +81,16 @@ describe('InstallationsRouter', () => {
}); });
it('query installations with limit = 0', (done) => { it('query installations with limit = 0', (done) => {
var config = Config.get('test'); const config = Config.get('test');
var androidDeviceRequest = { const androidDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'installationId': '12345678-abcd-abcd-abcd-123456789abc',
'deviceType': 'android' 'deviceType': 'android'
}; };
var iosDeviceRequest = { const iosDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'installationId': '12345678-abcd-abcd-abcd-123456789abd',
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: {}, body: {},
@@ -101,14 +101,14 @@ describe('InstallationsRouter', () => {
}; };
Config.get('test'); Config.get('test');
var router = new InstallationsRouter(); const router = new InstallationsRouter();
rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest)
.then(() => { .then(() => {
return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest);
}).then(() => { }).then(() => {
return router.handleFind(request); return router.handleFind(request);
}).then((res) => { }).then((res) => {
var response = res.response; const response = res.response;
expect(response.results.length).toEqual(0); expect(response.results.length).toEqual(0);
done(); done();
}).catch((err) => { }).catch((err) => {
@@ -118,16 +118,16 @@ describe('InstallationsRouter', () => {
}); });
it('query installations with count = 1', done => { it('query installations with count = 1', done => {
var config = Config.get('test'); const config = Config.get('test');
var androidDeviceRequest = { const androidDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'installationId': '12345678-abcd-abcd-abcd-123456789abc',
'deviceType': 'android' 'deviceType': 'android'
}; };
var iosDeviceRequest = { const iosDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'installationId': '12345678-abcd-abcd-abcd-123456789abd',
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: {}, body: {},
@@ -137,12 +137,12 @@ describe('InstallationsRouter', () => {
info: {} info: {}
}; };
var router = new InstallationsRouter(); const router = new InstallationsRouter();
rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest)
.then(() => rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest)) .then(() => rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest))
.then(() => router.handleFind(request)) .then(() => router.handleFind(request))
.then((res) => { .then((res) => {
var response = res.response; const response = res.response;
expect(response.results.length).toEqual(2); expect(response.results.length).toEqual(2);
expect(response.count).toEqual(2); expect(response.count).toEqual(2);
done(); done();
@@ -154,16 +154,16 @@ describe('InstallationsRouter', () => {
}); });
it('query installations with limit = 0 and count = 1', (done) => { it('query installations with limit = 0 and count = 1', (done) => {
var config = Config.get('test'); const config = Config.get('test');
var androidDeviceRequest = { const androidDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abc', 'installationId': '12345678-abcd-abcd-abcd-123456789abc',
'deviceType': 'android' 'deviceType': 'android'
}; };
var iosDeviceRequest = { const iosDeviceRequest = {
'installationId': '12345678-abcd-abcd-abcd-123456789abd', 'installationId': '12345678-abcd-abcd-abcd-123456789abd',
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var request = { const request = {
config: config, config: config,
auth: auth.master(config), auth: auth.master(config),
body: {}, body: {},
@@ -174,14 +174,14 @@ describe('InstallationsRouter', () => {
info: {} info: {}
}; };
var router = new InstallationsRouter(); const router = new InstallationsRouter();
rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest) rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest)
.then(() => { .then(() => {
return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest);
}).then(() => { }).then(() => {
return router.handleFind(request); return router.handleFind(request);
}).then((res) => { }).then((res) => {
var response = res.response; const response = res.response;
expect(response.results.length).toEqual(0); expect(response.results.length).toEqual(0);
expect(response.count).toEqual(2); expect(response.count).toEqual(2);
done(); done();

View File

@@ -35,23 +35,23 @@ describe('JobSchedule', () => {
'jobName': 'SomeJob' 'jobName': 'SomeJob'
}); });
jobSchedule.save(null).then(done.fail) jobSchedule.save(null).then(done.fail)
.catch(done); .catch(() => done());
}); });
it('should reject access when not using masterKey (/jobs)', (done) => { it('should reject access when not using masterKey (/jobs)', (done) => {
rp.get(Parse.serverURL + '/cloud_code/jobs', defaultOptions).then(done.fail, done); rp.get(Parse.serverURL + '/cloud_code/jobs', defaultOptions).then(done.fail, () => done());
}); });
it('should reject access when not using masterKey (/jobs/data)', (done) => { it('should reject access when not using masterKey (/jobs/data)', (done) => {
rp.get(Parse.serverURL + '/cloud_code/jobs/data', defaultOptions).then(done.fail, done); rp.get(Parse.serverURL + '/cloud_code/jobs/data', defaultOptions).then(done.fail, () => done());
}); });
it('should reject access when not using masterKey (PUT /jobs/id)', (done) => { it('should reject access when not using masterKey (PUT /jobs/id)', (done) => {
rp.put(Parse.serverURL + '/cloud_code/jobs/jobId', defaultOptions).then(done.fail, done); rp.put(Parse.serverURL + '/cloud_code/jobs/jobId', defaultOptions).then(done.fail, () => done());
}); });
it('should reject access when not using masterKey (PUT /jobs/id)', (done) => { it('should reject access when not using masterKey (PUT /jobs/id)', (done) => {
rp.del(Parse.serverURL + '/cloud_code/jobs/jobId', defaultOptions).then(done.fail, done); rp.del(Parse.serverURL + '/cloud_code/jobs/jobId', defaultOptions).then(done.fail, () => done());
}); });
it('should allow access when using masterKey (/jobs)', (done) => { it('should allow access when using masterKey (/jobs)', (done) => {
@@ -90,7 +90,7 @@ describe('JobSchedule', () => {
}); });
rp.post(Parse.serverURL + '/cloud_code/jobs', options) rp.post(Parse.serverURL + '/cloud_code/jobs', options)
.then(done.fail) .then(done.fail)
.catch(done); .catch(() => done());
}); });
it('should update a job', (done) => { it('should update a job', (done) => {
@@ -144,7 +144,7 @@ describe('JobSchedule', () => {
})); }));
}) })
.then(done.fail) .then(done.fail)
.catch(done); .catch(() => done());
}); });
it('should destroy a job', (done) => { it('should destroy a job', (done) => {

View File

@@ -1,5 +1,5 @@
var logging = require('../src/Adapters/Logger/WinstonLogger'); const logging = require('../src/Adapters/Logger/WinstonLogger');
var winston = require('winston'); const winston = require('winston');
class TestTransport extends winston.Transport { class TestTransport extends winston.Transport {
log(level, msg, meta, callback) { log(level, msg, meta, callback) {
@@ -51,7 +51,7 @@ describe('Logger', () => {
spyOn(process.stdout, 'write'); spyOn(process.stdout, 'write');
logging.logger.info('hi', {key: 'value'}); logging.logger.info('hi', {key: 'value'});
expect(process.stdout.write).toHaveBeenCalled(); expect(process.stdout.write).toHaveBeenCalled();
var firstLog = process.stdout.write.calls.first().args[0]; const firstLog = process.stdout.write.calls.first().args[0];
expect(firstLog).toEqual(JSON.stringify({key: 'value', level: 'info', message: 'hi' }) + '\n'); expect(firstLog).toEqual(JSON.stringify({key: 'value', level: 'info', message: 'hi' }) + '\n');
return reconfigureServer({ return reconfigureServer({
jsonLogs: false jsonLogs: false

View File

@@ -1,12 +1,12 @@
var LoggerController = require('../src/Controllers/LoggerController').LoggerController; const LoggerController = require('../src/Controllers/LoggerController').LoggerController;
var WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; const WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter;
describe('LoggerController', () => { describe('LoggerController', () => {
it('can check process a query without throwing', (done) => { it('can check process a query without throwing', (done) => {
// Make mock request // Make mock request
var query = {}; const query = {};
var loggerController = new LoggerController(new WinstonLoggerAdapter()); const loggerController = new LoggerController(new WinstonLoggerAdapter());
expect(() => { expect(() => {
loggerController.getLogs(query).then(function(res) { loggerController.getLogs(query).then(function(res) {
@@ -29,7 +29,7 @@ describe('LoggerController', () => {
it('can set the proper default values', (done) => { it('can set the proper default values', (done) => {
// Make mock request // Make mock request
var result = LoggerController.parseOptions(); const result = LoggerController.parseOptions();
expect(result.size).toEqual(10); expect(result.size).toEqual(10);
expect(result.order).toEqual('desc'); expect(result.order).toEqual('desc');
expect(result.level).toEqual('info'); expect(result.level).toEqual('info');
@@ -39,7 +39,7 @@ describe('LoggerController', () => {
it('can process a query without throwing', (done) => { it('can process a query without throwing', (done) => {
// Make mock request // Make mock request
var query = { const query = {
from: "2016-01-01Z00:00:00", from: "2016-01-01Z00:00:00",
until: "2016-01-01Z00:00:00", until: "2016-01-01Z00:00:00",
size: 5, size: 5,
@@ -47,7 +47,7 @@ describe('LoggerController', () => {
level: 'error' level: 'error'
}; };
var result = LoggerController.parseOptions(query); const result = LoggerController.parseOptions(query);
expect(result.from.getTime()).toEqual(1451606400000); expect(result.from.getTime()).toEqual(1451606400000);
expect(result.until.getTime()).toEqual(1451606400000); expect(result.until.getTime()).toEqual(1451606400000);
@@ -60,7 +60,7 @@ describe('LoggerController', () => {
it('can check process a query without throwing', (done) => { it('can check process a query without throwing', (done) => {
// Make mock request // Make mock request
var query = { const query = {
from: "2016-01-01", from: "2016-01-01",
until: "2016-01-30", until: "2016-01-30",
size: 5, size: 5,
@@ -68,7 +68,7 @@ describe('LoggerController', () => {
level: 'error' level: 'error'
}; };
var loggerController = new LoggerController(new WinstonLoggerAdapter()); const loggerController = new LoggerController(new WinstonLoggerAdapter());
expect(() => { expect(() => {
loggerController.getLogs(query).then(function(res) { loggerController.getLogs(query).then(function(res) {

View File

@@ -1,16 +1,16 @@
'use strict'; 'use strict';
const request = require('request'); const request = require('request');
var LogsRouter = require('../src/Routers/LogsRouter').LogsRouter; const LogsRouter = require('../src/Routers/LogsRouter').LogsRouter;
var LoggerController = require('../src/Controllers/LoggerController').LoggerController; const LoggerController = require('../src/Controllers/LoggerController').LoggerController;
var WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; const WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter;
const loggerController = new LoggerController(new WinstonLoggerAdapter()); const loggerController = new LoggerController(new WinstonLoggerAdapter());
describe('LogsRouter', () => { describe('LogsRouter', () => {
it('can check valid master key of request', (done) => { it('can check valid master key of request', (done) => {
// Make mock request // Make mock request
var request = { const request = {
auth: { auth: {
isMaster: true isMaster: true
}, },
@@ -20,7 +20,7 @@ describe('LogsRouter', () => {
} }
}; };
var router = new LogsRouter(); const router = new LogsRouter();
expect(() => { expect(() => {
router.validateRequest(request); router.validateRequest(request);
@@ -30,7 +30,7 @@ describe('LogsRouter', () => {
it('can check invalid construction of controller', (done) => { it('can check invalid construction of controller', (done) => {
// Make mock request // Make mock request
var request = { const request = {
auth: { auth: {
isMaster: true isMaster: true
}, },
@@ -40,7 +40,7 @@ describe('LogsRouter', () => {
} }
}; };
var router = new LogsRouter(); const router = new LogsRouter();
expect(() => { expect(() => {
router.validateRequest(request); router.validateRequest(request);

View File

@@ -1,9 +1,9 @@
var middlewares = require('../src/middlewares'); const middlewares = require('../src/middlewares');
var AppCache = require('../src/cache').AppCache; const AppCache = require('../src/cache').AppCache;
describe('middlewares', () => { describe('middlewares', () => {
var fakeReq, fakeRes; let fakeReq, fakeRes;
beforeEach(() => { beforeEach(() => {
fakeReq = { fakeReq = {
@@ -27,7 +27,7 @@ describe('middlewares', () => {
it('should use _ContentType if provided', (done) => { it('should use _ContentType if provided', (done) => {
expect(fakeReq.headers['content-type']).toEqual(undefined); expect(fakeReq.headers['content-type']).toEqual(undefined);
var contentType = 'image/jpeg'; const contentType = 'image/jpeg';
fakeReq.body._ContentType = contentType; fakeReq.body._ContentType = contentType;
middlewares.handleParseHeaders(fakeReq, fakeRes, () => { middlewares.handleParseHeaders(fakeReq, fakeRes, () => {
expect(fakeReq.headers['content-type']).toEqual(contentType); expect(fakeReq.headers['content-type']).toEqual(contentType);

View File

@@ -53,7 +53,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
.then(() => adapter._rawFind('Foo', {})) .then(() => adapter._rawFind('Foo', {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(obj._id).toEqual('abcde'); expect(obj._id).toEqual('abcde');
expect(obj.objectId).toBeUndefined(); expect(obj.objectId).toBeUndefined();
done(); done();

View File

@@ -7,8 +7,8 @@ const mongodb = require('mongodb');
describe('parseObjectToMongoObjectForCreate', () => { describe('parseObjectToMongoObjectForCreate', () => {
it('a basic number', (done) => { it('a basic number', (done) => {
var input = {five: 5}; const input = {five: 5};
var output = transform.parseObjectToMongoObjectForCreate(null, input, { const output = transform.parseObjectToMongoObjectForCreate(null, input, {
fields: {five: {type: 'Number'}} fields: {five: {type: 'Number'}}
}); });
jequal(input, output); jequal(input, output);
@@ -16,8 +16,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('an object with null values', (done) => { it('an object with null values', (done) => {
var input = {objectWithNullValues: {isNull: null, notNull: 3}}; const input = {objectWithNullValues: {isNull: null, notNull: 3}};
var output = transform.parseObjectToMongoObjectForCreate(null, input, { const output = transform.parseObjectToMongoObjectForCreate(null, input, {
fields: {objectWithNullValues: {type: 'object'}} fields: {objectWithNullValues: {type: 'object'}}
}); });
jequal(input, output); jequal(input, output);
@@ -25,23 +25,23 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('built-in timestamps', (done) => { it('built-in timestamps', (done) => {
var input = { const input = {
createdAt: "2015-10-06T21:24:50.332Z", createdAt: "2015-10-06T21:24:50.332Z",
updatedAt: "2015-10-06T21:24:50.332Z" updatedAt: "2015-10-06T21:24:50.332Z"
}; };
var output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} });
expect(output._created_at instanceof Date).toBe(true); expect(output._created_at instanceof Date).toBe(true);
expect(output._updated_at instanceof Date).toBe(true); expect(output._updated_at instanceof Date).toBe(true);
done(); done();
}); });
it('array of pointers', (done) => { it('array of pointers', (done) => {
var pointer = { const pointer = {
__type: 'Pointer', __type: 'Pointer',
objectId: 'myId', objectId: 'myId',
className: 'Blah', className: 'Blah',
}; };
var out = transform.parseObjectToMongoObjectForCreate(null, {pointers: [pointer]},{ const out = transform.parseObjectToMongoObjectForCreate(null, {pointers: [pointer]},{
fields: {pointers: {type: 'Array'}} fields: {pointers: {type: 'Array'}}
}); });
jequal([pointer], out.pointers); jequal([pointer], out.pointers);
@@ -51,21 +51,21 @@ describe('parseObjectToMongoObjectForCreate', () => {
//TODO: object creation requests shouldn't be seeing __op delete, it makes no sense to //TODO: object creation requests shouldn't be seeing __op delete, it makes no sense to
//have __op delete in a new object. Figure out what this should actually be testing. //have __op delete in a new object. Figure out what this should actually be testing.
xit('a delete op', (done) => { xit('a delete op', (done) => {
var input = {deleteMe: {__op: 'Delete'}}; const input = {deleteMe: {__op: 'Delete'}};
var output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} });
jequal(output, {}); jequal(output, {});
done(); done();
}); });
it('Doesnt allow ACL, as Parse Server should tranform ACL to _wperm + _rperm', done => { it('Doesnt allow ACL, as Parse Server should tranform ACL to _wperm + _rperm', done => {
var input = {ACL: {'0123': {'read': true, 'write': true}}}; const input = {ACL: {'0123': {'read': true, 'write': true}}};
expect(() => transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} })).toThrow(); expect(() => transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} })).toThrow();
done(); done();
}); });
it('plain', (done) => { it('plain', (done) => {
var geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; const geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180};
var out = transform.parseObjectToMongoObjectForCreate(null, {location: geoPoint},{ const out = transform.parseObjectToMongoObjectForCreate(null, {location: geoPoint},{
fields: {location: {type: 'GeoPoint'}} fields: {location: {type: 'GeoPoint'}}
}); });
expect(out.location).toEqual([180, -180]); expect(out.location).toEqual([180, -180]);
@@ -73,8 +73,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('in array', (done) => { it('in array', (done) => {
var geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; const geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180};
var out = transform.parseObjectToMongoObjectForCreate(null, {locations: [geoPoint, geoPoint]},{ const out = transform.parseObjectToMongoObjectForCreate(null, {locations: [geoPoint, geoPoint]},{
fields: {locations: {type: 'Array'}} fields: {locations: {type: 'Array'}}
}); });
expect(out.locations).toEqual([geoPoint, geoPoint]); expect(out.locations).toEqual([geoPoint, geoPoint]);
@@ -82,8 +82,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('in sub-object', (done) => { it('in sub-object', (done) => {
var geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180}; const geoPoint = {__type: 'GeoPoint', longitude: 180, latitude: -180};
var out = transform.parseObjectToMongoObjectForCreate(null, { locations: { start: geoPoint }},{ const out = transform.parseObjectToMongoObjectForCreate(null, { locations: { start: geoPoint }},{
fields: {locations: {type: 'Object'}} fields: {locations: {type: 'Object'}}
}); });
expect(out).toEqual({ locations: { start: geoPoint } }); expect(out).toEqual({ locations: { start: geoPoint } });
@@ -91,31 +91,31 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('objectId', (done) => { it('objectId', (done) => {
var out = transform.transformWhere(null, {objectId: 'foo'}); const out = transform.transformWhere(null, {objectId: 'foo'});
expect(out._id).toEqual('foo'); expect(out._id).toEqual('foo');
done(); done();
}); });
it('objectId in a list', (done) => { it('objectId in a list', (done) => {
var input = { const input = {
objectId: {'$in': ['one', 'two', 'three']}, objectId: {'$in': ['one', 'two', 'three']},
}; };
var output = transform.transformWhere(null, input); const output = transform.transformWhere(null, input);
jequal(input.objectId, output._id); jequal(input.objectId, output._id);
done(); done();
}); });
it('built-in timestamps', (done) => { it('built-in timestamps', (done) => {
var input = {createdAt: new Date(), updatedAt: new Date()}; const input = {createdAt: new Date(), updatedAt: new Date()};
var output = transform.mongoObjectToParseObject(null, input, { fields: {} }); const output = transform.mongoObjectToParseObject(null, input, { fields: {} });
expect(typeof output.createdAt).toEqual('string'); expect(typeof output.createdAt).toEqual('string');
expect(typeof output.updatedAt).toEqual('string'); expect(typeof output.updatedAt).toEqual('string');
done(); done();
}); });
it('pointer', (done) => { it('pointer', (done) => {
var input = {_p_userPointer: '_User$123'}; const input = {_p_userPointer: '_User$123'};
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields: { userPointer: { type: 'Pointer', targetClass: '_User' } }, fields: { userPointer: { type: 'Pointer', targetClass: '_User' } },
}); });
expect(typeof output.userPointer).toEqual('object'); expect(typeof output.userPointer).toEqual('object');
@@ -126,8 +126,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('null pointer', (done) => { it('null pointer', (done) => {
var input = {_p_userPointer: null}; const input = {_p_userPointer: null};
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields: { userPointer: { type: 'Pointer', targetClass: '_User' } }, fields: { userPointer: { type: 'Pointer', targetClass: '_User' } },
}); });
expect(output.userPointer).toBeUndefined(); expect(output.userPointer).toBeUndefined();
@@ -135,8 +135,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('file', (done) => { it('file', (done) => {
var input = {picture: 'pic.jpg'}; const input = {picture: 'pic.jpg'};
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields: { picture: { type: 'File' }}, fields: { picture: { type: 'File' }},
}); });
expect(typeof output.picture).toEqual('object'); expect(typeof output.picture).toEqual('object');
@@ -145,8 +145,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('geopoint', (done) => { it('geopoint', (done) => {
var input = {location: [45, -45]}; const input = {location: [45, -45]};
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields: { location: { type: 'GeoPoint' }}, fields: { location: { type: 'GeoPoint' }},
}); });
expect(typeof output.location).toEqual('object'); expect(typeof output.location).toEqual('object');
@@ -157,8 +157,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('polygon', (done) => { it('polygon', (done) => {
var input = {location: { type: 'Polygon', coordinates: [[[45, -45],[45, -45]]]}}; const input = {location: { type: 'Polygon', coordinates: [[[45, -45],[45, -45]]]}};
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields: { location: { type: 'Polygon' }}, fields: { location: { type: 'Polygon' }},
}); });
expect(typeof output.location).toEqual('object'); expect(typeof output.location).toEqual('object');
@@ -169,8 +169,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('bytes', (done) => { it('bytes', (done) => {
var input = {binaryData: "aGVsbG8gd29ybGQ="}; const input = {binaryData: "aGVsbG8gd29ybGQ="};
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields: { binaryData: { type: 'Bytes' }}, fields: { binaryData: { type: 'Bytes' }},
}); });
expect(typeof output.binaryData).toEqual('object'); expect(typeof output.binaryData).toEqual('object');
@@ -181,8 +181,8 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('nested array', (done) => { it('nested array', (done) => {
var input = {arr: [{_testKey: 'testValue' }]}; const input = {arr: [{_testKey: 'testValue' }]};
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields: { arr: { type: 'Array' } }, fields: { arr: { type: 'Array' } },
}); });
expect(Array.isArray(output.arr)).toEqual(true); expect(Array.isArray(output.arr)).toEqual(true);
@@ -210,10 +210,10 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('changes new pointer key', (done) => { it('changes new pointer key', (done) => {
var input = { const input = {
somePointer: {__type: 'Pointer', className: 'Micro', objectId: 'oft'} somePointer: {__type: 'Pointer', className: 'Micro', objectId: 'oft'}
}; };
var output = transform.parseObjectToMongoObjectForCreate(null, input, { const output = transform.parseObjectToMongoObjectForCreate(null, input, {
fields: {somePointer: {type: 'Pointer'}} fields: {somePointer: {type: 'Pointer'}}
}); });
expect(typeof output._p_somePointer).toEqual('string'); expect(typeof output._p_somePointer).toEqual('string');
@@ -222,10 +222,10 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('changes existing pointer keys', (done) => { it('changes existing pointer keys', (done) => {
var input = { const input = {
userPointer: {__type: 'Pointer', className: '_User', objectId: 'qwerty'} userPointer: {__type: 'Pointer', className: '_User', objectId: 'qwerty'}
}; };
var output = transform.parseObjectToMongoObjectForCreate(null, input, { const output = transform.parseObjectToMongoObjectForCreate(null, input, {
fields: {userPointer: {type: 'Pointer'}} fields: {userPointer: {type: 'Pointer'}}
}); });
expect(typeof output._p_userPointer).toEqual('string'); expect(typeof output._p_userPointer).toEqual('string');
@@ -234,12 +234,12 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('writes the old ACL format in addition to rperm and wperm on create', (done) => { it('writes the old ACL format in addition to rperm and wperm on create', (done) => {
var input = { const input = {
_rperm: ['*'], _rperm: ['*'],
_wperm: ['Kevin'], _wperm: ['Kevin'],
}; };
var output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} }); const output = transform.parseObjectToMongoObjectForCreate(null, input, { fields: {} });
expect(typeof output._acl).toEqual('object'); expect(typeof output._acl).toEqual('object');
expect(output._acl['Kevin'].w).toBeTruthy(); expect(output._acl['Kevin'].w).toBeTruthy();
expect(output._acl['Kevin'].r).toBeUndefined(); expect(output._acl['Kevin'].r).toBeUndefined();
@@ -249,10 +249,10 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('removes Relation types', (done) => { it('removes Relation types', (done) => {
var input = { const input = {
aRelation: { __type: 'Relation', className: 'Stuff' }, aRelation: { __type: 'Relation', className: 'Stuff' },
}; };
var output = transform.parseObjectToMongoObjectForCreate(null, input, { const output = transform.parseObjectToMongoObjectForCreate(null, input, {
fields: { fields: {
aRelation: { __type: 'Relation', className: 'Stuff' }, aRelation: { __type: 'Relation', className: 'Stuff' },
}, },
@@ -262,13 +262,13 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('writes the old ACL format in addition to rperm and wperm on update', (done) => { it('writes the old ACL format in addition to rperm and wperm on update', (done) => {
var input = { const input = {
_rperm: ['*'], _rperm: ['*'],
_wperm: ['Kevin'] _wperm: ['Kevin']
}; };
var output = transform.transformUpdate(null, input, { fields: {} }); const output = transform.transformUpdate(null, input, { fields: {} });
var set = output.$set; const set = output.$set;
expect(typeof set).toEqual('object'); expect(typeof set).toEqual('object');
expect(typeof set._acl).toEqual('object'); expect(typeof set._acl).toEqual('object');
expect(set._acl['Kevin'].w).toBeTruthy(); expect(set._acl['Kevin'].w).toBeTruthy();
@@ -279,11 +279,11 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('untransforms from _rperm and _wperm to ACL', (done) => { it('untransforms from _rperm and _wperm to ACL', (done) => {
var input = { const input = {
_rperm: ["*"], _rperm: ["*"],
_wperm: ["Kevin"] _wperm: ["Kevin"]
}; };
var output = transform.mongoObjectToParseObject(null, input, { fields: {} }); const output = transform.mongoObjectToParseObject(null, input, { fields: {} });
expect(output._rperm).toEqual(['*']); expect(output._rperm).toEqual(['*']);
expect(output._wperm).toEqual(['Kevin']); expect(output._wperm).toEqual(['Kevin']);
expect(output.ACL).toBeUndefined() expect(output.ACL).toBeUndefined()
@@ -291,11 +291,11 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('untransforms mongodb number types', (done) => { it('untransforms mongodb number types', (done) => {
var input = { const input = {
long: mongodb.Long.fromNumber(Number.MAX_SAFE_INTEGER), long: mongodb.Long.fromNumber(Number.MAX_SAFE_INTEGER),
double: new mongodb.Double(Number.MAX_VALUE) double: new mongodb.Double(Number.MAX_VALUE)
} }
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields: { fields: {
long: { type: 'Number' }, long: { type: 'Number' },
double: { type: 'Number' }, double: { type: 'Number' },
@@ -307,10 +307,10 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('Date object where iso attribute is of type Date', (done) => { it('Date object where iso attribute is of type Date', (done) => {
var input = { const input = {
ts : { __type: 'Date', iso: new Date('2017-01-18T00:00:00.000Z') } ts : { __type: 'Date', iso: new Date('2017-01-18T00:00:00.000Z') }
} }
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields : { fields : {
ts : { type : 'Date' } ts : { type : 'Date' }
} }
@@ -320,10 +320,10 @@ describe('parseObjectToMongoObjectForCreate', () => {
}); });
it('Date object where iso attribute is of type String', (done) => { it('Date object where iso attribute is of type String', (done) => {
var input = { const input = {
ts : { __type: 'Date', iso: '2017-01-18T00:00:00.000Z' } ts : { __type: 'Date', iso: '2017-01-18T00:00:00.000Z' }
} }
var output = transform.mongoObjectToParseObject(null, input, { const output = transform.mongoObjectToParseObject(null, input, {
fields : { fields : {
ts : { type : 'Date' } ts : { type : 'Date' }
} }
@@ -335,10 +335,10 @@ describe('parseObjectToMongoObjectForCreate', () => {
describe('transformUpdate', () => { describe('transformUpdate', () => {
it('removes Relation types', (done) => { it('removes Relation types', (done) => {
var input = { const input = {
aRelation: { __type: 'Relation', className: 'Stuff' }, aRelation: { __type: 'Relation', className: 'Stuff' },
}; };
var output = transform.transformUpdate(null, input, { const output = transform.transformUpdate(null, input, {
fields: { fields: {
aRelation: { __type: 'Relation', className: 'Stuff' }, aRelation: { __type: 'Relation', className: 'Stuff' },
}, },

View File

@@ -1,11 +1,11 @@
var NullCacheAdapter = require('../src/Adapters/Cache/NullCacheAdapter').default; const NullCacheAdapter = require('../src/Adapters/Cache/NullCacheAdapter').default;
describe('NullCacheAdapter', function() { describe('NullCacheAdapter', function() {
var KEY = 'hello'; const KEY = 'hello';
var VALUE = 'world'; const VALUE = 'world';
it('should expose promisifyed methods', (done) => { it('should expose promisifyed methods', (done) => {
var cache = new NullCacheAdapter({ const cache = new NullCacheAdapter({
ttl: NaN ttl: NaN
}); });
@@ -21,7 +21,7 @@ describe('NullCacheAdapter', function() {
}); });
it('should get/set/clear', (done) => { it('should get/set/clear', (done) => {
var cache = new NullCacheAdapter({ const cache = new NullCacheAdapter({
ttl: NaN ttl: NaN
}); });

View File

@@ -1,4 +1,4 @@
var OAuth = require("../src/Adapters/Auth/OAuth1Client"); const OAuth = require("../src/Adapters/Auth/OAuth1Client");
describe('OAuth', function() { describe('OAuth', function() {
it("Nonce should have right length", (done) => { it("Nonce should have right length", (done) => {
@@ -7,45 +7,45 @@ describe('OAuth', function() {
}); });
it("Should properly build parameter string", (done) => { it("Should properly build parameter string", (done) => {
var string = OAuth.buildParameterString({c:1, a:2, b:3}) const string = OAuth.buildParameterString({c:1, a:2, b:3})
jequal(string, "a=2&b=3&c=1"); jequal(string, "a=2&b=3&c=1");
done(); done();
}); });
it("Should properly build empty parameter string", (done) => { it("Should properly build empty parameter string", (done) => {
var string = OAuth.buildParameterString() const string = OAuth.buildParameterString()
jequal(string, ""); jequal(string, "");
done(); done();
}); });
it("Should properly build signature string", (done) => { it("Should properly build signature string", (done) => {
var string = OAuth.buildSignatureString("get", "http://dummy.com", ""); const string = OAuth.buildSignatureString("get", "http://dummy.com", "");
jequal(string, "GET&http%3A%2F%2Fdummy.com&"); jequal(string, "GET&http%3A%2F%2Fdummy.com&");
done(); done();
}); });
it("Should properly generate request signature", (done) => { it("Should properly generate request signature", (done) => {
var request = { let request = {
host: "dummy.com", host: "dummy.com",
path: "path" path: "path"
}; };
var oauth_params = { const oauth_params = {
oauth_timestamp: 123450000, oauth_timestamp: 123450000,
oauth_nonce: "AAAAAAAAAAAAAAAAA", oauth_nonce: "AAAAAAAAAAAAAAAAA",
oauth_consumer_key: "hello", oauth_consumer_key: "hello",
oauth_token: "token" oauth_token: "token"
}; };
var consumer_secret = "world"; const consumer_secret = "world";
var auth_token_secret = "secret"; const auth_token_secret = "secret";
request = OAuth.signRequest(request, oauth_params, consumer_secret, auth_token_secret); request = OAuth.signRequest(request, oauth_params, consumer_secret, auth_token_secret);
jequal(request.headers['Authorization'], 'OAuth oauth_consumer_key="hello", oauth_nonce="AAAAAAAAAAAAAAAAA", oauth_signature="8K95bpQcDi9Nd2GkhumTVcw4%2BXw%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="123450000", oauth_token="token", oauth_version="1.0"'); jequal(request.headers['Authorization'], 'OAuth oauth_consumer_key="hello", oauth_nonce="AAAAAAAAAAAAAAAAA", oauth_signature="8K95bpQcDi9Nd2GkhumTVcw4%2BXw%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="123450000", oauth_token="token", oauth_version="1.0"');
done(); done();
}); });
it("Should properly build request", (done) => { it("Should properly build request", (done) => {
var options = { const options = {
host: "dummy.com", host: "dummy.com",
consumer_key: "hello", consumer_key: "hello",
consumer_secret: "world", consumer_secret: "world",
@@ -57,11 +57,11 @@ describe('OAuth', function() {
oauth_nonce: "AAAAAAAAAAAAAAAAA" oauth_nonce: "AAAAAAAAAAAAAAAAA"
} }
}; };
var path = "path"; const path = "path";
var method = "get"; const method = "get";
var oauthClient = new OAuth(options); const oauthClient = new OAuth(options);
var req = oauthClient.buildRequest(method, path, {"query": "param"}); const req = oauthClient.buildRequest(method, path, {"query": "param"});
jequal(req.host, options.host); jequal(req.host, options.host);
jequal(req.path, "/" + path + "?query=param"); jequal(req.path, "/" + path + "?query=param");
@@ -75,7 +75,7 @@ describe('OAuth', function() {
function validateCannotAuthenticateError(data, done) { function validateCannotAuthenticateError(data, done) {
jequal(typeof data, "object"); jequal(typeof data, "object");
jequal(typeof data.errors, "object"); jequal(typeof data.errors, "object");
var errors = data.errors; const errors = data.errors;
jequal(typeof errors[0], "object"); jequal(typeof errors[0], "object");
// Cannot authenticate error // Cannot authenticate error
jequal(errors[0].code, 32); jequal(errors[0].code, 32);
@@ -83,48 +83,48 @@ describe('OAuth', function() {
} }
it("Should fail a GET request", (done) => { it("Should fail a GET request", (done) => {
var options = { const options = {
host: "api.twitter.com", host: "api.twitter.com",
consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX", consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX",
consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
}; };
var path = "/1.1/help/configuration.json"; const path = "/1.1/help/configuration.json";
var params = {"lang": "en"}; const params = {"lang": "en"};
var oauthClient = new OAuth(options); const oauthClient = new OAuth(options);
oauthClient.get(path, params).then(function(data){ oauthClient.get(path, params).then(function(data){
validateCannotAuthenticateError(data, done); validateCannotAuthenticateError(data, done);
}) })
}); });
it("Should fail a POST request", (done) => { it("Should fail a POST request", (done) => {
var options = { const options = {
host: "api.twitter.com", host: "api.twitter.com",
consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX", consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX",
consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
}; };
var body = { const body = {
lang: "en" lang: "en"
}; };
var path = "/1.1/account/settings.json"; const path = "/1.1/account/settings.json";
var oauthClient = new OAuth(options); const oauthClient = new OAuth(options);
oauthClient.post(path, null, body).then(function(data){ oauthClient.post(path, null, body).then(function(data){
validateCannotAuthenticateError(data, done); validateCannotAuthenticateError(data, done);
}) })
}); });
it("Should fail a request", (done) => { it("Should fail a request", (done) => {
var options = { const options = {
host: "localhost", host: "localhost",
consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX", consumer_key: "XXXXXXXXXXXXXXXXXXXXXXXXX",
consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", consumer_secret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
}; };
var body = { const body = {
lang: "en" lang: "en"
}; };
var path = "/"; const path = "/";
var oauthClient = new OAuth(options); const oauthClient = new OAuth(options);
oauthClient.post(path, null, body).then(function(){ oauthClient.post(path, null, body).then(function(){
jequal(false, true); jequal(false, true);
done(); done();
@@ -135,7 +135,7 @@ describe('OAuth', function() {
}); });
it("Should fail with missing options", (done) => { it("Should fail with missing options", (done) => {
var options = undefined; const options = undefined;
try { try {
new OAuth(options); new OAuth(options);
} catch (error) { } catch (error) {

View File

@@ -9,12 +9,12 @@ const delayPromise = (delay) => {
} }
describe('Parse.Push', () => { describe('Parse.Push', () => {
var setup = function() { const setup = function() {
var sendToInstallationSpy = jasmine.createSpy(); const sendToInstallationSpy = jasmine.createSpy();
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
var badge = body.data.badge; const badge = body.data.badge;
const promises = installations.map((installation) => { const promises = installations.map((installation) => {
sendToInstallationSpy(installation); sendToInstallationSpy(installation);
@@ -46,9 +46,9 @@ describe('Parse.Push', () => {
} }
}) })
.then(() => { .then(() => {
var installations = []; const installations = [];
while(installations.length != 10) { while(installations.length != 10) {
var installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
installation.set("deviceToken","device_token_" + installations.length) installation.set("deviceToken","device_token_" + installations.length)
installation.set("badge", installations.length); installation.set("badge", installations.length);

View File

@@ -1,12 +1,12 @@
// This is a port of the test suite: // This is a port of the test suite:
// hungry/js/test/parse_acl_test.js // hungry/js/test/parse_acl_test.js
var rest = require('../src/rest'); const rest = require('../src/rest');
var Config = require('../src/Config'); const Config = require('../src/Config');
var auth = require('../src/Auth'); const auth = require('../src/Auth');
describe('Parse.ACL', () => { describe('Parse.ACL', () => {
it("acl must be valid", (done) => { it("acl must be valid", (done) => {
var user = new Parse.User(); const user = new Parse.User();
ok(!user.setACL("Ceci n'est pas un ACL.", { ok(!user.setACL("Ceci n'est pas un ACL.", {
error: function(user, error) { error: function(user, error) {
equal(error.code, -1); equal(error.code, -1);
@@ -17,13 +17,13 @@ describe('Parse.ACL', () => {
it("refresh object with acl", (done) => { it("refresh object with acl", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -41,13 +41,13 @@ describe('Parse.ACL', () => {
it("acl an object owned by one user and public get", (done) => { it("acl an object owned by one user and public get", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -60,7 +60,7 @@ describe('Parse.ACL', () => {
Parse.User.logOut() Parse.User.logOut()
.then(() => { .then(() => {
// Get // Get
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.get(object.id, { query.get(object.id, {
success: function() { success: function() {
fail('Should not have retrieved the object.'); fail('Should not have retrieved the object.');
@@ -80,13 +80,13 @@ describe('Parse.ACL', () => {
it("acl an object owned by one user and public find", (done) => { it("acl an object owned by one user and public find", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -100,7 +100,7 @@ describe('Parse.ACL', () => {
Parse.User.logOut() Parse.User.logOut()
.then(() => { .then(() => {
// Find // Find
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 0); equal(results.length, 0);
@@ -117,13 +117,13 @@ describe('Parse.ACL', () => {
it("acl an object owned by one user and public update", (done) => { it("acl an object owned by one user and public update", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -156,13 +156,13 @@ describe('Parse.ACL', () => {
it("acl an object owned by one user and public delete", (done) => { it("acl an object owned by one user and public delete", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -190,13 +190,13 @@ describe('Parse.ACL', () => {
it("acl an object owned by one user and logged in get", (done) => { it("acl an object owned by one user and logged in get", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -211,7 +211,7 @@ describe('Parse.ACL', () => {
Parse.User.logIn("alice", "wonderland", { Parse.User.logIn("alice", "wonderland", {
success: function() { success: function() {
// Get // Get
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.get(object.id, { query.get(object.id, {
success: function(result) { success: function(result) {
ok(result); ok(result);
@@ -235,13 +235,13 @@ describe('Parse.ACL', () => {
it("acl an object owned by one user and logged in find", (done) => { it("acl an object owned by one user and logged in find", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -256,11 +256,11 @@ describe('Parse.ACL', () => {
Parse.User.logIn("alice", "wonderland", { Parse.User.logIn("alice", "wonderland", {
success: function() { success: function() {
// Find // Find
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 1); equal(results.length, 1);
var result = results[0]; const result = results[0];
ok(result); ok(result);
if (!result) { if (!result) {
return fail(); return fail();
@@ -285,13 +285,13 @@ describe('Parse.ACL', () => {
it("acl an object owned by one user and logged in update", (done) => { it("acl an object owned by one user and logged in update", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -323,13 +323,13 @@ describe('Parse.ACL', () => {
it("acl an object owned by one user and logged in delete", (done) => { it("acl an object owned by one user and logged in delete", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -360,13 +360,13 @@ describe('Parse.ACL', () => {
it("acl making an object publicly readable and public get", (done) => { it("acl making an object publicly readable and public get", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -389,7 +389,7 @@ describe('Parse.ACL', () => {
Parse.User.logOut() Parse.User.logOut()
.then(() => { .then(() => {
// Get // Get
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.get(object.id, { query.get(object.id, {
success: function(result) { success: function(result) {
ok(result); ok(result);
@@ -408,13 +408,13 @@ describe('Parse.ACL', () => {
it("acl making an object publicly readable and public find", (done) => { it("acl making an object publicly readable and public find", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -437,11 +437,11 @@ describe('Parse.ACL', () => {
Parse.User.logOut() Parse.User.logOut()
.then(() => { .then(() => {
// Find // Find
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 1); equal(results.length, 1);
var result = results[0]; const result = results[0];
ok(result); ok(result);
equal(result.id, object.id); equal(result.id, object.id);
done(); done();
@@ -458,13 +458,13 @@ describe('Parse.ACL', () => {
it("acl making an object publicly readable and public update", (done) => { it("acl making an object publicly readable and public update", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -505,13 +505,13 @@ describe('Parse.ACL', () => {
it("acl making an object publicly readable and public delete", (done) => { it("acl making an object publicly readable and public delete", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -549,13 +549,13 @@ describe('Parse.ACL', () => {
it("acl making an object publicly writable and public get", (done) => { it("acl making an object publicly writable and public get", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -578,7 +578,7 @@ describe('Parse.ACL', () => {
Parse.User.logOut() Parse.User.logOut()
.then(() => { .then(() => {
// Get // Get
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.get(object.id, { query.get(object.id, {
error: function(model, error) { error: function(model, error) {
equal(error.code, Parse.Error.OBJECT_NOT_FOUND); equal(error.code, Parse.Error.OBJECT_NOT_FOUND);
@@ -596,13 +596,13 @@ describe('Parse.ACL', () => {
it("acl making an object publicly writable and public find", (done) => { it("acl making an object publicly writable and public find", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -625,7 +625,7 @@ describe('Parse.ACL', () => {
Parse.User.logOut() Parse.User.logOut()
.then(() => { .then(() => {
// Find // Find
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 0); equal(results.length, 0);
@@ -643,13 +643,13 @@ describe('Parse.ACL', () => {
it("acl making an object publicly writable and public update", (done) => { it("acl making an object publicly writable and public update", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -689,13 +689,13 @@ describe('Parse.ACL', () => {
it("acl making an object publicly writable and public delete", (done) => { it("acl making an object publicly writable and public delete", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp(null, { user.signUp(null, {
success: function() { success: function() {
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
object.setACL(acl); object.setACL(acl);
object.save(null, { object.save(null, {
success: function() { success: function() {
@@ -734,14 +734,14 @@ describe('Parse.ACL', () => {
it("acl making an object privately writable (#3194)", (done) => { it("acl making an object privately writable (#3194)", (done) => {
// Create an object owned by Alice. // Create an object owned by Alice.
var object; let object;
var user2; let user2;
var user = new Parse.User(); const user = new Parse.User();
user.set("username", "alice"); user.set("username", "alice");
user.set("password", "wonderland"); user.set("password", "wonderland");
user.signUp().then(() => { user.signUp().then(() => {
object = new TestObject(); object = new TestObject();
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
acl.setPublicWriteAccess(false); acl.setPublicWriteAccess(false);
acl.setPublicReadAccess(true); acl.setPublicReadAccess(true);
object.setACL(acl); object.setACL(acl);
@@ -774,8 +774,8 @@ describe('Parse.ACL', () => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
// Create an object shared by Bob and Alice. // Create an object shared by Bob and Alice.
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
acl.setWriteAccess(bob, true); acl.setWriteAccess(bob, true);
acl.setReadAccess(bob, true); acl.setReadAccess(bob, true);
object.setACL(acl); object.setACL(acl);
@@ -791,7 +791,7 @@ describe('Parse.ACL', () => {
// Sign in as Bob again. // Sign in as Bob again.
Parse.User.logIn("bob", "pass", { Parse.User.logIn("bob", "pass", {
success: function() { success: function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.get(object.id, { query.get(object.id, {
success: function(result) { success: function(result) {
ok(result); ok(result);
@@ -820,8 +820,8 @@ describe('Parse.ACL', () => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
// Create an object shared by Bob and Alice. // Create an object shared by Bob and Alice.
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
acl.setWriteAccess(bob, true); acl.setWriteAccess(bob, true);
acl.setReadAccess(bob, true); acl.setReadAccess(bob, true);
object.setACL(acl); object.setACL(acl);
@@ -837,11 +837,11 @@ describe('Parse.ACL', () => {
// Sign in as Bob again. // Sign in as Bob again.
Parse.User.logIn("bob", "pass", { Parse.User.logIn("bob", "pass", {
success: function() { success: function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 1); equal(results.length, 1);
var result = results[0]; const result = results[0];
ok(result); ok(result);
if (!result) { if (!result) {
fail("should have result"); fail("should have result");
@@ -872,8 +872,8 @@ describe('Parse.ACL', () => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
// Create an object shared by Bob and Alice. // Create an object shared by Bob and Alice.
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
acl.setWriteAccess(bob, true); acl.setWriteAccess(bob, true);
acl.setReadAccess(bob, true); acl.setReadAccess(bob, true);
object.setACL(acl); object.setACL(acl);
@@ -916,8 +916,8 @@ describe('Parse.ACL', () => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
// Create an object shared by Bob and Alice. // Create an object shared by Bob and Alice.
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
acl.setWriteAccess(bob, true); acl.setWriteAccess(bob, true);
acl.setReadAccess(bob, true); acl.setReadAccess(bob, true);
object.setACL(acl); object.setACL(acl);
@@ -960,8 +960,8 @@ describe('Parse.ACL', () => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
// Create an object shared by Bob and Alice. // Create an object shared by Bob and Alice.
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
acl.setWriteAccess(bob, true); acl.setWriteAccess(bob, true);
acl.setReadAccess(bob, true); acl.setReadAccess(bob, true);
object.setACL(acl); object.setACL(acl);
@@ -977,7 +977,7 @@ describe('Parse.ACL', () => {
// Start making requests by the public. // Start making requests by the public.
Parse.User.logOut() Parse.User.logOut()
.then(() => { .then(() => {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.get(object.id).then((result) => { query.get(object.id).then((result) => {
fail(result); fail(result);
}, (error) => { }, (error) => {
@@ -1004,8 +1004,8 @@ describe('Parse.ACL', () => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
// Create an object shared by Bob and Alice. // Create an object shared by Bob and Alice.
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
acl.setWriteAccess(bob, true); acl.setWriteAccess(bob, true);
acl.setReadAccess(bob, true); acl.setReadAccess(bob, true);
object.setACL(acl); object.setACL(acl);
@@ -1021,7 +1021,7 @@ describe('Parse.ACL', () => {
// Start making requests by the public. // Start making requests by the public.
Parse.User.logOut() Parse.User.logOut()
.then(() => { .then(() => {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 0); equal(results.length, 0);
@@ -1048,8 +1048,8 @@ describe('Parse.ACL', () => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
// Create an object shared by Bob and Alice. // Create an object shared by Bob and Alice.
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
acl.setWriteAccess(bob, true); acl.setWriteAccess(bob, true);
acl.setReadAccess(bob, true); acl.setReadAccess(bob, true);
object.setACL(acl); object.setACL(acl);
@@ -1092,8 +1092,8 @@ describe('Parse.ACL', () => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
// Create an object shared by Bob and Alice. // Create an object shared by Bob and Alice.
var object = new TestObject(); const object = new TestObject();
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
acl.setWriteAccess(bob, true); acl.setWriteAccess(bob, true);
acl.setReadAccess(bob, true); acl.setReadAccess(bob, true);
object.setACL(acl); object.setACL(acl);
@@ -1127,10 +1127,10 @@ describe('Parse.ACL', () => {
it("acl saveAll with permissions", (done) => { it("acl saveAll with permissions", (done) => {
Parse.User.signUp("alice", "wonderland", null, { Parse.User.signUp("alice", "wonderland", null, {
success: function(alice) { success: function(alice) {
var acl = new Parse.ACL(alice); const acl = new Parse.ACL(alice);
var object1 = new TestObject(); const object1 = new TestObject();
var object2 = new TestObject(); const object2 = new TestObject();
object1.setACL(acl); object1.setACL(acl);
object2.setACL(acl); object2.setACL(acl);
Parse.Object.saveAll([object1, object2], { Parse.Object.saveAll([object1, object2], {
@@ -1149,7 +1149,7 @@ describe('Parse.ACL', () => {
object2.set("foo", "bar"); object2.set("foo", "bar");
Parse.Object.saveAll([object1, object2], { Parse.Object.saveAll([object1, object2], {
success: function() { success: function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.equalTo("foo", "bar"); query.equalTo("foo", "bar");
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -1193,16 +1193,16 @@ describe('Parse.ACL', () => {
}); });
it("query for included object with ACL works", (done) => { it("query for included object with ACL works", (done) => {
var obj1 = new Parse.Object("TestClass1"); const obj1 = new Parse.Object("TestClass1");
var obj2 = new Parse.Object("TestClass2"); const obj2 = new Parse.Object("TestClass2");
var acl = new Parse.ACL(); const acl = new Parse.ACL();
acl.setPublicReadAccess(true); acl.setPublicReadAccess(true);
obj2.set("ACL", acl); obj2.set("ACL", acl);
obj1.set("other", obj2); obj1.set("other", obj2);
obj1.save(null, expectSuccess({ obj1.save(null, expectSuccess({
success: function() { success: function() {
obj2._clearServerData(); obj2._clearServerData();
var query = new Parse.Query("TestClass1"); const query = new Parse.Query("TestClass1");
query.first(expectSuccess({ query.first(expectSuccess({
success: function(obj1Again) { success: function(obj1Again) {
ok(!obj1Again.get("other").get("ACL")); ok(!obj1Again.get("other").get("ACL"));
@@ -1221,11 +1221,11 @@ describe('Parse.ACL', () => {
}); });
it('restricted ACL does not have public access', (done) => { it('restricted ACL does not have public access', (done) => {
var obj = new Parse.Object("TestClassMasterACL"); const obj = new Parse.Object("TestClassMasterACL");
var acl = new Parse.ACL(); const acl = new Parse.ACL();
obj.set('ACL', acl); obj.set('ACL', acl);
obj.save().then(() => { obj.save().then(() => {
var query = new Parse.Query("TestClassMasterACL"); const query = new Parse.Query("TestClassMasterACL");
return query.find(); return query.find();
}).then((results) => { }).then((results) => {
ok(!results.length, 'Should not have returned object with secure ACL.'); ok(!results.length, 'Should not have returned object with secure ACL.');
@@ -1235,7 +1235,7 @@ describe('Parse.ACL', () => {
it('regression test #701', done => { it('regression test #701', done => {
const config = Config.get('test'); const config = Config.get('test');
var anonUser = { const anonUser = {
authData: { authData: {
anonymous: { anonymous: {
id: '00000000-0000-0000-0000-000000000001' id: '00000000-0000-0000-0000-000000000001'
@@ -1245,8 +1245,8 @@ describe('Parse.ACL', () => {
Parse.Cloud.afterSave(Parse.User, req => { Parse.Cloud.afterSave(Parse.User, req => {
if (!req.object.existed()) { if (!req.object.existed()) {
var user = req.object; const user = req.object;
var acl = new Parse.ACL(user); const acl = new Parse.ACL(user);
user.setACL(acl); user.setACL(acl);
user.save(null, {useMasterKey: true}).then(user => { user.save(null, {useMasterKey: true}).then(user => {
new Parse.Query('_User').get(user.objectId).then(() => { new Parse.Query('_User').get(user.objectId).then(() => {

View File

@@ -2,24 +2,24 @@
// It would probably be better to refactor them into different files. // It would probably be better to refactor them into different files.
'use strict'; 'use strict';
var request = require('request'); const request = require('request');
const rp = require('request-promise'); const rp = require('request-promise');
const Parse = require("parse/node"); const Parse = require("parse/node");
const Config = require('../src/Config'); const Config = require('../src/Config');
const SchemaController = require('../src/Controllers/SchemaController'); const SchemaController = require('../src/Controllers/SchemaController');
var TestUtils = require('../src/TestUtils'); const TestUtils = require('../src/TestUtils');
const userSchema = SchemaController.convertSchemaToAdapterSchema({ className: '_User', fields: Object.assign({}, SchemaController.defaultColumns._Default, SchemaController.defaultColumns._User) }); const userSchema = SchemaController.convertSchemaToAdapterSchema({ className: '_User', fields: Object.assign({}, SchemaController.defaultColumns._Default, SchemaController.defaultColumns._User) });
describe_only_db('mongo')('miscellaneous', () => { describe_only_db('mongo')('miscellaneous', () => {
it('test rest_create_app', function(done) { it('test rest_create_app', function(done) {
var appId; let appId;
Parse._request('POST', 'rest_create_app').then((res) => { Parse._request('POST', 'rest_create_app').then((res) => {
expect(typeof res.application_id).toEqual('string'); expect(typeof res.application_id).toEqual('string');
expect(res.master_key).toEqual('master'); expect(res.master_key).toEqual('master');
appId = res.application_id; appId = res.application_id;
Parse.initialize(appId, 'unused'); Parse.initialize(appId, 'unused');
var obj = new Parse.Object('TestObject'); const obj = new Parse.Object('TestObject');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
return obj.save(); return obj.save();
}).then(() => { }).then(() => {
@@ -38,7 +38,7 @@ describe_only_db('mongo')('miscellaneous', () => {
describe('miscellaneous', function() { describe('miscellaneous', function() {
it('create a GameScore object', function(done) { it('create a GameScore object', function(done) {
var obj = new Parse.Object('GameScore'); const obj = new Parse.Object('GameScore');
obj.set('score', 1337); obj.set('score', 1337);
obj.save().then(function(obj) { obj.save().then(function(obj) {
expect(typeof obj.id).toBe('string'); expect(typeof obj.id).toBe('string');
@@ -52,7 +52,7 @@ describe('miscellaneous', function() {
it('get a TestObject', function(done) { it('get a TestObject', function(done) {
create({ 'bloop' : 'blarg' }, function(obj) { create({ 'bloop' : 'blarg' }, function(obj) {
var t2 = new TestObject({ objectId: obj.id }); const t2 = new TestObject({ objectId: obj.id });
t2.fetch({ t2.fetch({
success: function(obj2) { success: function(obj2) {
expect(obj2.get('bloop')).toEqual('blarg'); expect(obj2.get('bloop')).toEqual('blarg');
@@ -277,12 +277,12 @@ describe('miscellaneous', function() {
}); });
it('save various data types', function(done) { it('save various data types', function(done) {
var obj = new TestObject(); const obj = new TestObject();
obj.set('date', new Date()); obj.set('date', new Date());
obj.set('array', [1, 2, 3]); obj.set('array', [1, 2, 3]);
obj.set('object', {one: 1, two: 2}); obj.set('object', {one: 1, two: 2});
obj.save().then(() => { obj.save().then(() => {
var obj2 = new TestObject({objectId: obj.id}); const obj2 = new TestObject({objectId: obj.id});
return obj2.fetch(); return obj2.fetch();
}).then((obj2) => { }).then((obj2) => {
expect(obj2.get('date') instanceof Date).toBe(true); expect(obj2.get('date') instanceof Date).toBe(true);
@@ -294,12 +294,12 @@ describe('miscellaneous', function() {
}); });
it('query with limit', function(done) { it('query with limit', function(done) {
var baz = new TestObject({ foo: 'baz' }); const baz = new TestObject({ foo: 'baz' });
var qux = new TestObject({ foo: 'qux' }); const qux = new TestObject({ foo: 'qux' });
baz.save().then(() => { baz.save().then(() => {
return qux.save(); return qux.save();
}).then(() => { }).then(() => {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.limit(1); query.limit(1);
return query.find(); return query.find();
}).then((results) => { }).then((results) => {
@@ -312,8 +312,8 @@ describe('miscellaneous', function() {
}); });
it('query without limit get default 100 records', function(done) { it('query without limit get default 100 records', function(done) {
var objects = []; const objects = [];
for (var i = 0; i < 150; i++) { for (let i = 0; i < 150; i++) {
objects.push(new TestObject({name: 'name' + i})); objects.push(new TestObject({name: 'name' + i}));
} }
Parse.Object.saveAll(objects).then(() => { Parse.Object.saveAll(objects).then(() => {
@@ -328,8 +328,8 @@ describe('miscellaneous', function() {
}); });
it('basic saveAll', function(done) { it('basic saveAll', function(done) {
var alpha = new TestObject({ letter: 'alpha' }); const alpha = new TestObject({ letter: 'alpha' });
var beta = new TestObject({ letter: 'beta' }); const beta = new TestObject({ letter: 'beta' });
Parse.Object.saveAll([alpha, beta]).then(() => { Parse.Object.saveAll([alpha, beta]).then(() => {
expect(alpha.id).toBeTruthy(); expect(alpha.id).toBeTruthy();
expect(beta.id).toBeTruthy(); expect(beta.id).toBeTruthy();
@@ -344,7 +344,7 @@ describe('miscellaneous', function() {
}); });
it('test beforeSave set object acl success', function(done) { it('test beforeSave set object acl success', function(done) {
var acl = new Parse.ACL({ const acl = new Parse.ACL({
'*': { read: true, write: false } '*': { read: true, write: false }
}); });
Parse.Cloud.beforeSave('BeforeSaveAddACL', function(req, res) { Parse.Cloud.beforeSave('BeforeSaveAddACL', function(req, res) {
@@ -352,10 +352,10 @@ describe('miscellaneous', function() {
res.success(); res.success();
}); });
var obj = new Parse.Object('BeforeSaveAddACL'); const obj = new Parse.Object('BeforeSaveAddACL');
obj.set('lol', true); obj.set('lol', true);
obj.save().then(function() { obj.save().then(function() {
var query = new Parse.Query('BeforeSaveAddACL'); const query = new Parse.Query('BeforeSaveAddACL');
query.get(obj.id).then(function(objAgain) { query.get(obj.id).then(function(objAgain) {
expect(objAgain.get('lol')).toBeTruthy(); expect(objAgain.get('lol')).toBeTruthy();
expect(objAgain.getACL().equals(acl)); expect(objAgain.getACL().equals(acl));
@@ -534,20 +534,20 @@ describe('miscellaneous', function() {
it('pointer reassign is working properly (#1288)', (done) => { it('pointer reassign is working properly (#1288)', (done) => {
Parse.Cloud.beforeSave('GameScore', (req, res) => { Parse.Cloud.beforeSave('GameScore', (req, res) => {
var obj = req.object; const obj = req.object;
if (obj.get('point')) { if (obj.get('point')) {
return res.success(); return res.success();
} }
var TestObject1 = Parse.Object.extend('TestObject1'); const TestObject1 = Parse.Object.extend('TestObject1');
var newObj = new TestObject1({'key1': 1}); const newObj = new TestObject1({'key1': 1});
return newObj.save().then((newObj) => { return newObj.save().then((newObj) => {
obj.set('point' , newObj); obj.set('point' , newObj);
res.success(); res.success();
}); });
}); });
var pointId; let pointId;
var obj = new Parse.Object('GameScore'); const obj = new Parse.Object('GameScore');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.save().then(() => { obj.save().then(() => {
expect(obj.get('point')).not.toBeUndefined(); expect(obj.get('point')).not.toBeUndefined();
@@ -562,10 +562,10 @@ describe('miscellaneous', function() {
}); });
it('test afterSave get full object on create and update', function(done) { it('test afterSave get full object on create and update', function(done) {
var triggerTime = 0; let triggerTime = 0;
// Register a mock beforeSave hook // Register a mock beforeSave hook
Parse.Cloud.afterSave('GameScore', function(req, res) { Parse.Cloud.afterSave('GameScore', function(req, res) {
var object = req.object; const object = req.object;
expect(object instanceof Parse.Object).toBeTruthy(); expect(object instanceof Parse.Object).toBeTruthy();
expect(object.id).not.toBeUndefined(); expect(object.id).not.toBeUndefined();
expect(object.createdAt).not.toBeUndefined(); expect(object.createdAt).not.toBeUndefined();
@@ -584,7 +584,7 @@ describe('miscellaneous', function() {
res.success(); res.success();
}); });
var obj = new Parse.Object('GameScore'); const obj = new Parse.Object('GameScore');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.set('fooAgain', 'barAgain'); obj.set('fooAgain', 'barAgain');
obj.save().then(function() { obj.save().then(function() {
@@ -602,17 +602,17 @@ describe('miscellaneous', function() {
}); });
it('test afterSave get original object on update', function(done) { it('test afterSave get original object on update', function(done) {
var triggerTime = 0; let triggerTime = 0;
// Register a mock beforeSave hook // Register a mock beforeSave hook
Parse.Cloud.afterSave('GameScore', function(req, res) { Parse.Cloud.afterSave('GameScore', function(req, res) {
var object = req.object; const object = req.object;
expect(object instanceof Parse.Object).toBeTruthy(); expect(object instanceof Parse.Object).toBeTruthy();
expect(object.get('fooAgain')).toEqual('barAgain'); expect(object.get('fooAgain')).toEqual('barAgain');
expect(object.id).not.toBeUndefined(); expect(object.id).not.toBeUndefined();
expect(object.createdAt).not.toBeUndefined(); expect(object.createdAt).not.toBeUndefined();
expect(object.updatedAt).not.toBeUndefined(); expect(object.updatedAt).not.toBeUndefined();
var originalObject = req.original; const originalObject = req.original;
if (triggerTime == 0) { if (triggerTime == 0) {
// Create // Create
expect(object.get('foo')).toEqual('bar'); expect(object.get('foo')).toEqual('bar');
@@ -635,7 +635,7 @@ describe('miscellaneous', function() {
res.success(); res.success();
}); });
var obj = new Parse.Object('GameScore'); const obj = new Parse.Object('GameScore');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.set('fooAgain', 'barAgain'); obj.set('fooAgain', 'barAgain');
obj.save().then(function() { obj.save().then(function() {
@@ -653,11 +653,11 @@ describe('miscellaneous', function() {
}); });
it('test afterSave get full original object even req auth can not query it', (done) => { it('test afterSave get full original object even req auth can not query it', (done) => {
var triggerTime = 0; let triggerTime = 0;
// Register a mock beforeSave hook // Register a mock beforeSave hook
Parse.Cloud.afterSave('GameScore', function(req, res) { Parse.Cloud.afterSave('GameScore', function(req, res) {
var object = req.object; const object = req.object;
var originalObject = req.original; const originalObject = req.original;
if (triggerTime == 0) { if (triggerTime == 0) {
// Create // Create
} else if (triggerTime == 1) { } else if (triggerTime == 1) {
@@ -677,10 +677,10 @@ describe('miscellaneous', function() {
res.success(); res.success();
}); });
var obj = new Parse.Object('GameScore'); const obj = new Parse.Object('GameScore');
obj.set('foo', 'bar'); obj.set('foo', 'bar');
obj.set('fooAgain', 'barAgain'); obj.set('fooAgain', 'barAgain');
var acl = new Parse.ACL(); const acl = new Parse.ACL();
// Make sure our update request can not query the object // Make sure our update request can not query the object
acl.setPublicReadAccess(false); acl.setPublicReadAccess(false);
acl.setPublicWriteAccess(true); acl.setPublicWriteAccess(true);
@@ -700,7 +700,7 @@ describe('miscellaneous', function() {
}); });
it('afterSave flattens custom operations', done => { it('afterSave flattens custom operations', done => {
var triggerTime = 0; let triggerTime = 0;
// Register a mock beforeSave hook // Register a mock beforeSave hook
Parse.Cloud.afterSave('GameScore', function(req, res) { Parse.Cloud.afterSave('GameScore', function(req, res) {
const object = req.object; const object = req.object;
@@ -721,7 +721,7 @@ describe('miscellaneous', function() {
res.success(); res.success();
}); });
var obj = new Parse.Object('GameScore'); const obj = new Parse.Object('GameScore');
obj.increment('yolo', 1); obj.increment('yolo', 1);
obj.save().then(() => { obj.save().then(() => {
obj.increment('yolo', 1); obj.increment('yolo', 1);
@@ -817,7 +817,7 @@ describe('miscellaneous', function() {
it('should return the updated fields on PUT', done => { it('should return the updated fields on PUT', done => {
const obj = new Parse.Object('GameScore'); const obj = new Parse.Object('GameScore');
obj.save({a:'hello', c: 1, d: ['1'], e:['1'], f:['1','2']}).then(() => { obj.save({a:'hello', c: 1, d: ['1'], e:['1'], f:['1','2']}).then(() => {
var headers = { const headers = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest', 'X-Parse-REST-API-Key': 'rest',
@@ -921,7 +921,7 @@ describe('miscellaneous', function() {
expect(req.installationId).toEqual('yolo'); expect(req.installationId).toEqual('yolo');
}); });
var headers = { const headers = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest', 'X-Parse-REST-API-Key': 'rest',
@@ -952,7 +952,7 @@ describe('miscellaneous', function() {
expect(req.installationId).toEqual('yolo'); expect(req.installationId).toEqual('yolo');
}); });
var headers = { const headers = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest', 'X-Parse-REST-API-Key': 'rest',
@@ -979,7 +979,7 @@ describe('miscellaneous', function() {
Parse.Cloud.define('echoParams', (req, res) => { Parse.Cloud.define('echoParams', (req, res) => {
res.success(req.params); res.success(req.params);
}); });
var headers = { const headers = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-Javascript-Key': 'test' 'X-Parse-Javascript-Key': 'test'
@@ -994,7 +994,7 @@ describe('miscellaneous', function() {
body: '{"foo":"bar", "other": 1}' body: '{"foo":"bar", "other": 1}'
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var res = JSON.parse(body).result; const res = JSON.parse(body).result;
expect(res.option).toEqual('1'); expect(res.option).toEqual('1');
// Make sure query string params override body params // Make sure query string params override body params
expect(res.other).toEqual('2'); expect(res.other).toEqual('2');
@@ -1054,7 +1054,7 @@ describe('miscellaneous', function() {
}); });
it('fails on invalid client key', done => { it('fails on invalid client key', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-Client-Key': 'notclient' 'X-Parse-Client-Key': 'notclient'
@@ -1064,14 +1064,14 @@ describe('miscellaneous', function() {
url: 'http://localhost:8378/1/classes/TestObject' url: 'http://localhost:8378/1/classes/TestObject'
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.error).toEqual('unauthorized'); expect(b.error).toEqual('unauthorized');
done(); done();
}); });
}); });
it('fails on invalid windows key', done => { it('fails on invalid windows key', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-Windows-Key': 'notwindows' 'X-Parse-Windows-Key': 'notwindows'
@@ -1081,14 +1081,14 @@ describe('miscellaneous', function() {
url: 'http://localhost:8378/1/classes/TestObject' url: 'http://localhost:8378/1/classes/TestObject'
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.error).toEqual('unauthorized'); expect(b.error).toEqual('unauthorized');
done(); done();
}); });
}); });
it('fails on invalid javascript key', done => { it('fails on invalid javascript key', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-Javascript-Key': 'notjavascript' 'X-Parse-Javascript-Key': 'notjavascript'
@@ -1098,14 +1098,14 @@ describe('miscellaneous', function() {
url: 'http://localhost:8378/1/classes/TestObject' url: 'http://localhost:8378/1/classes/TestObject'
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.error).toEqual('unauthorized'); expect(b.error).toEqual('unauthorized');
done(); done();
}); });
}); });
it('fails on invalid rest api key', done => { it('fails on invalid rest api key', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'notrest' 'X-Parse-REST-API-Key': 'notrest'
@@ -1115,7 +1115,7 @@ describe('miscellaneous', function() {
url: 'http://localhost:8378/1/classes/TestObject' url: 'http://localhost:8378/1/classes/TestObject'
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.error).toEqual('unauthorized'); expect(b.error).toEqual('unauthorized');
done(); done();
}); });
@@ -1442,7 +1442,7 @@ describe('miscellaneous', function() {
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key': 'test' 'X-Parse-Master-Key': 'test'
}; };
var user, object; let user, object;
createTestUser().then((x) => { createTestUser().then((x) => {
user = x; user = x;
const acl = new Parse.ACL(); const acl = new Parse.ACL();

View File

@@ -1,10 +1,10 @@
var ParseCloudCodePublisher = require('../src/LiveQuery/ParseCloudCodePublisher').ParseCloudCodePublisher; const ParseCloudCodePublisher = require('../src/LiveQuery/ParseCloudCodePublisher').ParseCloudCodePublisher;
var Parse = require('parse/node'); const Parse = require('parse/node');
describe('ParseCloudCodePublisher', function() { describe('ParseCloudCodePublisher', function() {
beforeEach(function(done) { beforeEach(function(done) {
// Mock ParsePubSub // Mock ParsePubSub
var mockParsePubSub = { const mockParsePubSub = {
createPublisher: jasmine.createSpy('publish').and.returnValue({ createPublisher: jasmine.createSpy('publish').and.returnValue({
publish: jasmine.createSpy('publish'), publish: jasmine.createSpy('publish'),
on: jasmine.createSpy('on') on: jasmine.createSpy('on')
@@ -19,46 +19,46 @@ describe('ParseCloudCodePublisher', function() {
}); });
it('can initialize', function() { it('can initialize', function() {
var config = {} const config = {}
new ParseCloudCodePublisher(config); new ParseCloudCodePublisher(config);
var ParsePubSub = require('../src/LiveQuery/ParsePubSub').ParsePubSub; const ParsePubSub = require('../src/LiveQuery/ParsePubSub').ParsePubSub;
expect(ParsePubSub.createPublisher).toHaveBeenCalledWith(config); expect(ParsePubSub.createPublisher).toHaveBeenCalledWith(config);
}); });
it('can handle cloud code afterSave request', function() { it('can handle cloud code afterSave request', function() {
var publisher = new ParseCloudCodePublisher({}); const publisher = new ParseCloudCodePublisher({});
publisher._onCloudCodeMessage = jasmine.createSpy('onCloudCodeMessage'); publisher._onCloudCodeMessage = jasmine.createSpy('onCloudCodeMessage');
var request = {}; const request = {};
publisher.onCloudCodeAfterSave(request); publisher.onCloudCodeAfterSave(request);
expect(publisher._onCloudCodeMessage).toHaveBeenCalledWith(Parse.applicationId + 'afterSave', request); expect(publisher._onCloudCodeMessage).toHaveBeenCalledWith(Parse.applicationId + 'afterSave', request);
}); });
it('can handle cloud code afterDelete request', function() { it('can handle cloud code afterDelete request', function() {
var publisher = new ParseCloudCodePublisher({}); const publisher = new ParseCloudCodePublisher({});
publisher._onCloudCodeMessage = jasmine.createSpy('onCloudCodeMessage'); publisher._onCloudCodeMessage = jasmine.createSpy('onCloudCodeMessage');
var request = {}; const request = {};
publisher.onCloudCodeAfterDelete(request); publisher.onCloudCodeAfterDelete(request);
expect(publisher._onCloudCodeMessage).toHaveBeenCalledWith(Parse.applicationId + 'afterDelete', request); expect(publisher._onCloudCodeMessage).toHaveBeenCalledWith(Parse.applicationId + 'afterDelete', request);
}); });
it('can handle cloud code request', function() { it('can handle cloud code request', function() {
var publisher = new ParseCloudCodePublisher({}); const publisher = new ParseCloudCodePublisher({});
var currentParseObject = new Parse.Object('Test'); const currentParseObject = new Parse.Object('Test');
currentParseObject.set('key', 'value'); currentParseObject.set('key', 'value');
var originalParseObject = new Parse.Object('Test'); const originalParseObject = new Parse.Object('Test');
originalParseObject.set('key', 'originalValue'); originalParseObject.set('key', 'originalValue');
var request = { const request = {
object: currentParseObject, object: currentParseObject,
original: originalParseObject original: originalParseObject
}; };
publisher._onCloudCodeMessage('afterSave', request); publisher._onCloudCodeMessage('afterSave', request);
var args = publisher.parsePublisher.publish.calls.mostRecent().args; const args = publisher.parsePublisher.publish.calls.mostRecent().args;
expect(args[0]).toBe('afterSave'); expect(args[0]).toBe('afterSave');
var message = JSON.parse(args[1]); const message = JSON.parse(args[1]);
expect(message.currentParseObject).toEqual(request.object._toFullJSON()); expect(message.currentParseObject).toEqual(request.object._toFullJSON());
expect(message.originalParseObject).toEqual(request.original._toFullJSON()); expect(message.originalParseObject).toEqual(request.original._toFullJSON());
}); });

View File

@@ -3,18 +3,18 @@
"use strict"; "use strict";
var request = require('request'); const request = require('request');
var str = "Hello World!"; const str = "Hello World!";
var data = []; const data = [];
for (var i = 0; i < str.length; i++) { for (let i = 0; i < str.length; i++) {
data.push(str.charCodeAt(i)); data.push(str.charCodeAt(i));
} }
describe('Parse.File testing', () => { describe('Parse.File testing', () => {
describe('creating files', () => { describe('creating files', () => {
it('works with Content-Type', done => { it('works with Content-Type', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -25,7 +25,7 @@ describe('Parse.File testing', () => {
body: 'argle bargle', body: 'argle bargle',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.name).toMatch(/_file.txt$/); expect(b.name).toMatch(/_file.txt$/);
expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/);
request.get(b.url, (error, response, body) => { request.get(b.url, (error, response, body) => {
@@ -49,7 +49,7 @@ describe('Parse.File testing', () => {
}) })
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.name).toMatch(/_file.html/); expect(b.name).toMatch(/_file.html/);
expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.html$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.html$/);
request.get(b.url, (error, response, body) => { request.get(b.url, (error, response, body) => {
@@ -66,7 +66,7 @@ describe('Parse.File testing', () => {
}); });
it('works without Content-Type', done => { it('works without Content-Type', done => {
var headers = { const headers = {
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
}; };
@@ -76,7 +76,7 @@ describe('Parse.File testing', () => {
body: 'argle bargle', body: 'argle bargle',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.name).toMatch(/_file.txt$/); expect(b.name).toMatch(/_file.txt$/);
expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/);
request.get(b.url, (error, response, body) => { request.get(b.url, (error, response, body) => {
@@ -89,7 +89,7 @@ describe('Parse.File testing', () => {
}); });
it('supports REST end-to-end file create, read, delete, read', done => { it('supports REST end-to-end file create, read, delete, read', done => {
var headers = { const headers = {
'Content-Type': 'image/jpeg', 'Content-Type': 'image/jpeg',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -100,7 +100,7 @@ describe('Parse.File testing', () => {
body: 'check one two', body: 'check one two',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.name).toMatch(/_testfile.txt$/); expect(b.name).toMatch(/_testfile.txt$/);
expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*testfile.txt$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*testfile.txt$/);
request.get(b.url, (error, response, body) => { request.get(b.url, (error, response, body) => {
@@ -137,7 +137,7 @@ describe('Parse.File testing', () => {
}); });
it('blocks file deletions with missing or incorrect master-key header', done => { it('blocks file deletions with missing or incorrect master-key header', done => {
var headers = { const headers = {
'Content-Type': 'image/jpeg', 'Content-Type': 'image/jpeg',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -148,7 +148,7 @@ describe('Parse.File testing', () => {
body: 'the file body' body: 'the file body'
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*thefile.jpg$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*thefile.jpg$/);
// missing X-Parse-Master-Key header // missing X-Parse-Master-Key header
request.del({ request.del({
@@ -159,7 +159,7 @@ describe('Parse.File testing', () => {
url: 'http://localhost:8378/1/files/' + b.name url: 'http://localhost:8378/1/files/' + b.name
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var del_b = JSON.parse(body); const del_b = JSON.parse(body);
expect(response.statusCode).toEqual(403); expect(response.statusCode).toEqual(403);
expect(del_b.error).toMatch(/unauthorized/); expect(del_b.error).toMatch(/unauthorized/);
// incorrect X-Parse-Master-Key header // incorrect X-Parse-Master-Key header
@@ -172,7 +172,7 @@ describe('Parse.File testing', () => {
url: 'http://localhost:8378/1/files/' + b.name url: 'http://localhost:8378/1/files/' + b.name
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var del_b2 = JSON.parse(body); const del_b2 = JSON.parse(body);
expect(response.statusCode).toEqual(403); expect(response.statusCode).toEqual(403);
expect(del_b2.error).toMatch(/unauthorized/); expect(del_b2.error).toMatch(/unauthorized/);
done(); done();
@@ -182,7 +182,7 @@ describe('Parse.File testing', () => {
}); });
it('handles other filetypes', done => { it('handles other filetypes', done => {
var headers = { const headers = {
'Content-Type': 'image/jpeg', 'Content-Type': 'image/jpeg',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -193,7 +193,7 @@ describe('Parse.File testing', () => {
body: 'argle bargle', body: 'argle bargle',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.name).toMatch(/_file.jpg$/); expect(b.name).toMatch(/_file.jpg$/);
expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/.*file.jpg$/); expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/.*file.jpg$/);
request.get(b.url, (error, response, body) => { request.get(b.url, (error, response, body) => {
@@ -205,7 +205,7 @@ describe('Parse.File testing', () => {
}); });
it("save file", done => { it("save file", done => {
var file = new Parse.File("hello.txt", data, "text/plain"); const file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url()); ok(!file.url());
file.save(expectSuccess({ file.save(expectSuccess({
success: function(result) { success: function(result) {
@@ -219,7 +219,7 @@ describe('Parse.File testing', () => {
}); });
it("save file in object", done => { it("save file in object", done => {
var file = new Parse.File("hello.txt", data, "text/plain"); const file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url()); ok(!file.url());
file.save(expectSuccess({ file.save(expectSuccess({
success: function(result) { success: function(result) {
@@ -228,7 +228,7 @@ describe('Parse.File testing', () => {
ok(file.url()); ok(file.url());
notEqual(file.name(), "hello.txt"); notEqual(file.name(), "hello.txt");
var object = new Parse.Object("TestObject"); const object = new Parse.Object("TestObject");
object.save({ object.save({
file: file file: file
}, expectSuccess({ }, expectSuccess({
@@ -246,7 +246,7 @@ describe('Parse.File testing', () => {
}); });
it("save file in object with escaped characters in filename", done => { it("save file in object with escaped characters in filename", done => {
var file = new Parse.File("hello . txt", data, "text/plain"); const file = new Parse.File("hello . txt", data, "text/plain");
ok(!file.url()); ok(!file.url());
file.save(expectSuccess({ file.save(expectSuccess({
success: function(result) { success: function(result) {
@@ -255,7 +255,7 @@ describe('Parse.File testing', () => {
ok(file.url()); ok(file.url());
notEqual(file.name(), "hello . txt"); notEqual(file.name(), "hello . txt");
var object = new Parse.Object("TestObject"); const object = new Parse.Object("TestObject");
object.save({ object.save({
file: file file: file
}, expectSuccess({ }, expectSuccess({
@@ -274,9 +274,9 @@ describe('Parse.File testing', () => {
}); });
it("autosave file in object", done => { it("autosave file in object", done => {
var file = new Parse.File("hello.txt", data, "text/plain"); let file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url()); ok(!file.url());
var object = new Parse.Object("TestObject"); const object = new Parse.Object("TestObject");
object.save({ object.save({
file: file file: file
}, expectSuccess({ }, expectSuccess({
@@ -296,22 +296,22 @@ describe('Parse.File testing', () => {
}); });
it("autosave file in object in object", done => { it("autosave file in object in object", done => {
var file = new Parse.File("hello.txt", data, "text/plain"); let file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url()); ok(!file.url());
var child = new Parse.Object("Child"); const child = new Parse.Object("Child");
child.set("file", file); child.set("file", file);
var parent = new Parse.Object("Parent"); const parent = new Parse.Object("Parent");
parent.set("child", child); parent.set("child", child);
parent.save(expectSuccess({ parent.save(expectSuccess({
success: function(parent) { success: function(parent) {
var query = new Parse.Query("Parent"); const query = new Parse.Query("Parent");
query.include("child"); query.include("child");
query.get(parent.id, expectSuccess({ query.get(parent.id, expectSuccess({
success: function(parentAgain) { success: function(parentAgain) {
var childAgain = parentAgain.get("child"); const childAgain = parentAgain.get("child");
file = childAgain.get("file"); file = childAgain.get("file");
ok(file instanceof Parse.File); ok(file instanceof Parse.File);
ok(file.name()); ok(file.name());
@@ -325,7 +325,7 @@ describe('Parse.File testing', () => {
}); });
it("saving an already saved file", done => { it("saving an already saved file", done => {
var file = new Parse.File("hello.txt", data, "text/plain"); const file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url()); ok(!file.url());
file.save(expectSuccess({ file.save(expectSuccess({
success: function(result) { success: function(result) {
@@ -333,7 +333,7 @@ describe('Parse.File testing', () => {
ok(file.name()); ok(file.name());
ok(file.url()); ok(file.url());
notEqual(file.name(), "hello.txt"); notEqual(file.name(), "hello.txt");
var previousName = file.name(); const previousName = file.name();
file.save(expectSuccess({ file.save(expectSuccess({
success: function() { success: function() {
@@ -346,13 +346,13 @@ describe('Parse.File testing', () => {
}); });
it("two saves at the same time", done => { it("two saves at the same time", done => {
var file = new Parse.File("hello.txt", data, "text/plain"); const file = new Parse.File("hello.txt", data, "text/plain");
var firstName; let firstName;
var secondName; let secondName;
var firstSave = file.save().then(function() { firstName = file.name(); }); const firstSave = file.save().then(function() { firstName = file.name(); });
var secondSave = file.save().then(function() { secondName = file.name(); }); const secondSave = file.save().then(function() { secondName = file.name(); });
Parse.Promise.when(firstSave, secondSave).then(function() { Parse.Promise.when(firstSave, secondSave).then(function() {
equal(firstName, secondName); equal(firstName, secondName);
@@ -364,9 +364,9 @@ describe('Parse.File testing', () => {
}); });
it("file toJSON testing", done => { it("file toJSON testing", done => {
var file = new Parse.File("hello.txt", data, "text/plain"); const file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url()); ok(!file.url());
var object = new Parse.Object("TestObject"); const object = new Parse.Object("TestObject");
object.save({ object.save({
file: file file: file
}, expectSuccess({ }, expectSuccess({
@@ -378,7 +378,7 @@ describe('Parse.File testing', () => {
}); });
it("content-type used with no extension", done => { it("content-type used with no extension", done => {
var headers = { const headers = {
'Content-Type': 'text/html', 'Content-Type': 'text/html',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -389,7 +389,7 @@ describe('Parse.File testing', () => {
body: 'fee fi fo', body: 'fee fi fo',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.name).toMatch(/\.html$/); expect(b.name).toMatch(/\.html$/);
request.get(b.url, (error, response) => { request.get(b.url, (error, response) => {
if (!response) { if (!response) {
@@ -403,7 +403,7 @@ describe('Parse.File testing', () => {
}); });
it("filename is url encoded", done => { it("filename is url encoded", done => {
var headers = { const headers = {
'Content-Type': 'text/html', 'Content-Type': 'text/html',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -414,26 +414,26 @@ describe('Parse.File testing', () => {
body: 'oh emm gee', body: 'oh emm gee',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.url).toMatch(/hello%20world/); expect(b.url).toMatch(/hello%20world/);
done(); done();
}) })
}); });
it('supports array of files', done => { it('supports array of files', done => {
var file = { const file = {
__type: 'File', __type: 'File',
url: 'http://meep.meep', url: 'http://meep.meep',
name: 'meep' name: 'meep'
}; };
var files = [file, file]; const files = [file, file];
var obj = new Parse.Object('FilesArrayTest'); const obj = new Parse.Object('FilesArrayTest');
obj.set('files', files); obj.set('files', files);
obj.save().then(() => { obj.save().then(() => {
var query = new Parse.Query('FilesArrayTest'); const query = new Parse.Query('FilesArrayTest');
return query.first(); return query.first();
}).then((result) => { }).then((result) => {
var filesAgain = result.get('files'); const filesAgain = result.get('files');
expect(filesAgain.length).toEqual(2); expect(filesAgain.length).toEqual(2);
expect(filesAgain[0].name()).toEqual('meep'); expect(filesAgain[0].name()).toEqual('meep');
expect(filesAgain[0].url()).toEqual('http://meep.meep'); expect(filesAgain[0].url()).toEqual('http://meep.meep');
@@ -442,7 +442,7 @@ describe('Parse.File testing', () => {
}); });
it('validates filename characters', done => { it('validates filename characters', done => {
var headers = { const headers = {
'Content-Type': 'text/plain', 'Content-Type': 'text/plain',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -452,19 +452,19 @@ describe('Parse.File testing', () => {
url: 'http://localhost:8378/1/files/di$avowed.txt', url: 'http://localhost:8378/1/files/di$avowed.txt',
body: 'will fail', body: 'will fail',
}, (error, response, body) => { }, (error, response, body) => {
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.code).toEqual(122); expect(b.code).toEqual(122);
done(); done();
}); });
}); });
it('validates filename length', done => { it('validates filename length', done => {
var headers = { const headers = {
'Content-Type': 'text/plain', 'Content-Type': 'text/plain',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
}; };
var fileName = 'Onceuponamidnightdrearywhileiponderedweak' + const fileName = 'Onceuponamidnightdrearywhileiponderedweak' +
'andwearyOveramanyquaintandcuriousvolumeof' + 'andwearyOveramanyquaintandcuriousvolumeof' +
'forgottenloreWhileinoddednearlynappingsud' + 'forgottenloreWhileinoddednearlynappingsud' +
'denlytherecameatapping'; 'denlytherecameatapping';
@@ -473,30 +473,30 @@ describe('Parse.File testing', () => {
url: 'http://localhost:8378/1/files/' + fileName, url: 'http://localhost:8378/1/files/' + fileName,
body: 'will fail', body: 'will fail',
}, (error, response, body) => { }, (error, response, body) => {
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.code).toEqual(122); expect(b.code).toEqual(122);
done(); done();
}); });
}); });
it('supports a dictionary with file', done => { it('supports a dictionary with file', done => {
var file = { const file = {
__type: 'File', __type: 'File',
url: 'http://meep.meep', url: 'http://meep.meep',
name: 'meep' name: 'meep'
}; };
var dict = { const dict = {
file: file file: file
}; };
var obj = new Parse.Object('FileObjTest'); const obj = new Parse.Object('FileObjTest');
obj.set('obj', dict); obj.set('obj', dict);
obj.save().then(() => { obj.save().then(() => {
var query = new Parse.Query('FileObjTest'); const query = new Parse.Query('FileObjTest');
return query.first(); return query.first();
}).then((result) => { }).then((result) => {
var dictAgain = result.get('obj'); const dictAgain = result.get('obj');
expect(typeof dictAgain).toEqual('object'); expect(typeof dictAgain).toEqual('object');
var fileAgain = dictAgain['file']; const fileAgain = dictAgain['file'];
expect(fileAgain.name()).toEqual('meep'); expect(fileAgain.name()).toEqual('meep');
expect(fileAgain.url()).toEqual('http://meep.meep'); expect(fileAgain.url()).toEqual('http://meep.meep');
done(); done();
@@ -507,18 +507,18 @@ describe('Parse.File testing', () => {
}); });
it('creates correct url for old files hosted on files.parsetfss.com', done => { it('creates correct url for old files hosted on files.parsetfss.com', done => {
var file = { const file = {
__type: 'File', __type: 'File',
url: 'http://irrelevant.elephant/', url: 'http://irrelevant.elephant/',
name: 'tfss-123.txt' name: 'tfss-123.txt'
}; };
var obj = new Parse.Object('OldFileTest'); const obj = new Parse.Object('OldFileTest');
obj.set('oldfile', file); obj.set('oldfile', file);
obj.save().then(() => { obj.save().then(() => {
var query = new Parse.Query('OldFileTest'); const query = new Parse.Query('OldFileTest');
return query.first(); return query.first();
}).then((result) => { }).then((result) => {
var fileAgain = result.get('oldfile'); const fileAgain = result.get('oldfile');
expect(fileAgain.url()).toEqual( expect(fileAgain.url()).toEqual(
'http://files.parsetfss.com/test/tfss-123.txt' 'http://files.parsetfss.com/test/tfss-123.txt'
); );
@@ -530,18 +530,18 @@ describe('Parse.File testing', () => {
}); });
it('creates correct url for old files hosted on files.parse.com', done => { it('creates correct url for old files hosted on files.parse.com', done => {
var file = { const file = {
__type: 'File', __type: 'File',
url: 'http://irrelevant.elephant/', url: 'http://irrelevant.elephant/',
name: 'd6e80979-a128-4c57-a167-302f874700dc-123.txt' name: 'd6e80979-a128-4c57-a167-302f874700dc-123.txt'
}; };
var obj = new Parse.Object('OldFileTest'); const obj = new Parse.Object('OldFileTest');
obj.set('oldfile', file); obj.set('oldfile', file);
obj.save().then(() => { obj.save().then(() => {
var query = new Parse.Query('OldFileTest'); const query = new Parse.Query('OldFileTest');
return query.first(); return query.first();
}).then((result) => { }).then((result) => {
var fileAgain = result.get('oldfile'); const fileAgain = result.get('oldfile');
expect(fileAgain.url()).toEqual( expect(fileAgain.url()).toEqual(
'http://files.parse.com/test/d6e80979-a128-4c57-a167-302f874700dc-123.txt' 'http://files.parse.com/test/d6e80979-a128-4c57-a167-302f874700dc-123.txt'
); );
@@ -553,14 +553,14 @@ describe('Parse.File testing', () => {
}); });
it('supports files in objects without urls', done => { it('supports files in objects without urls', done => {
var file = { const file = {
__type: 'File', __type: 'File',
name: '123.txt' name: '123.txt'
}; };
var obj = new Parse.Object('FileTest'); const obj = new Parse.Object('FileTest');
obj.set('file', file); obj.set('file', file);
obj.save().then(() => { obj.save().then(() => {
var query = new Parse.Query('FileTest'); const query = new Parse.Query('FileTest');
return query.first(); return query.first();
}).then(result => { }).then(result => {
const fileAgain = result.get('file'); const fileAgain = result.get('file');
@@ -576,15 +576,15 @@ describe('Parse.File testing', () => {
reconfigureServer({ reconfigureServer({
publicServerURL: 'https://mydomain/parse' publicServerURL: 'https://mydomain/parse'
}).then(() => { }).then(() => {
var file = { const file = {
__type: 'File', __type: 'File',
name: '123.txt' name: '123.txt'
}; };
var obj = new Parse.Object('FileTest'); const obj = new Parse.Object('FileTest');
obj.set('file', file); obj.set('file', file);
return obj.save() return obj.save()
}).then(() => { }).then(() => {
var query = new Parse.Query('FileTest'); const query = new Parse.Query('FileTest');
return query.first(); return query.first();
}).then(result => { }).then(result => {
const fileAgain = result.get('file'); const fileAgain = result.get('file');
@@ -597,7 +597,7 @@ describe('Parse.File testing', () => {
}); });
it('fails to upload an empty file', done => { it('fails to upload an empty file', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -615,7 +615,7 @@ describe('Parse.File testing', () => {
}); });
it('fails to upload without a file name', done => { it('fails to upload without a file name', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -633,7 +633,7 @@ describe('Parse.File testing', () => {
}); });
it('fails to upload without a file name', done => { it('fails to upload without a file name', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -651,7 +651,7 @@ describe('Parse.File testing', () => {
}); });
it('fails to delete an unkown file', done => { it('fails to delete an unkown file', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest', 'X-Parse-REST-API-Key': 'rest',
@@ -670,7 +670,7 @@ describe('Parse.File testing', () => {
describe_only_db('mongo')('Gridstore Range tests', () => { describe_only_db('mongo')('Gridstore Range tests', () => {
it('supports range requests', done => { it('supports range requests', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -681,7 +681,7 @@ describe('Parse.File testing', () => {
body: 'argle bargle', body: 'argle bargle',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
request.get({ url: b.url, headers: { request.get({ url: b.url, headers: {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
@@ -696,7 +696,7 @@ describe('Parse.File testing', () => {
}); });
it('supports small range requests', done => { it('supports small range requests', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -707,7 +707,7 @@ describe('Parse.File testing', () => {
body: 'argle bargle', body: 'argle bargle',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
request.get({ url: b.url, headers: { request.get({ url: b.url, headers: {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
@@ -723,7 +723,7 @@ describe('Parse.File testing', () => {
// See specs https://www.greenbytes.de/tech/webdav/draft-ietf-httpbis-p5-range-latest.html#byte.ranges // See specs https://www.greenbytes.de/tech/webdav/draft-ietf-httpbis-p5-range-latest.html#byte.ranges
it('supports getting one byte', done => { it('supports getting one byte', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -734,7 +734,7 @@ describe('Parse.File testing', () => {
body: 'argle bargle', body: 'argle bargle',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
request.get({ url: b.url, headers: { request.get({ url: b.url, headers: {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
@@ -749,7 +749,7 @@ describe('Parse.File testing', () => {
}); });
it('supports getting last n bytes', done => { it('supports getting last n bytes', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -760,7 +760,7 @@ describe('Parse.File testing', () => {
body: 'something different', body: 'something different',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
request.get({ url: b.url, headers: { request.get({ url: b.url, headers: {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
@@ -776,7 +776,7 @@ describe('Parse.File testing', () => {
}); });
it('supports getting first n bytes', done => { it('supports getting first n bytes', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -787,7 +787,7 @@ describe('Parse.File testing', () => {
body: 'something different', body: 'something different',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
request.get({ url: b.url, headers: { request.get({ url: b.url, headers: {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
@@ -802,7 +802,7 @@ describe('Parse.File testing', () => {
}); });
function repeat(string, count) { function repeat(string, count) {
var s = string; let s = string;
while (count > 0) { while (count > 0) {
s += string; s += string;
count--; count--;
@@ -811,7 +811,7 @@ describe('Parse.File testing', () => {
} }
it('supports large range requests', done => { it('supports large range requests', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -822,7 +822,7 @@ describe('Parse.File testing', () => {
body: repeat('argle bargle', 100) body: repeat('argle bargle', 100)
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
request.get({ url: b.url, headers: { request.get({ url: b.url, headers: {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
@@ -856,7 +856,7 @@ describe('Parse.File testing', () => {
// for fallback tests // for fallback tests
describe_only_db('postgres')('Default Range tests', () => { describe_only_db('postgres')('Default Range tests', () => {
it('fallback to regular request', done => { it('fallback to regular request', done => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -867,7 +867,7 @@ describe('Parse.File testing', () => {
body: 'argle bargle', body: 'argle bargle',
}, (error, response, body) => { }, (error, response, body) => {
expect(error).toBe(null); expect(error).toBe(null);
var b = JSON.parse(body); const b = JSON.parse(body);
request.get({ url: b.url, headers: { request.get({ url: b.url, headers: {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',

View File

@@ -2,22 +2,22 @@
// hungry/js/test/parse_geo_point_test.js // hungry/js/test/parse_geo_point_test.js
const rp = require('request-promise'); const rp = require('request-promise');
var TestObject = Parse.Object.extend('TestObject'); const TestObject = Parse.Object.extend('TestObject');
describe('Parse.GeoPoint testing', () => { describe('Parse.GeoPoint testing', () => {
it('geo point roundtrip', (done) => { it('geo point roundtrip', (done) => {
var point = new Parse.GeoPoint(44.0, -11.0); const point = new Parse.GeoPoint(44.0, -11.0);
var obj = new TestObject(); const obj = new TestObject();
obj.set('location', point); obj.set('location', point);
obj.set('name', 'Ferndale'); obj.set('name', 'Ferndale');
obj.save(null, { obj.save(null, {
success: function() { success: function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 1); equal(results.length, 1);
var pointAgain = results[0].get('location'); const pointAgain = results[0].get('location');
ok(pointAgain); ok(pointAgain);
equal(pointAgain.latitude, 44.0); equal(pointAgain.latitude, 44.0);
equal(pointAgain.longitude, -11.0); equal(pointAgain.longitude, -11.0);
@@ -37,7 +37,7 @@ describe('Parse.GeoPoint testing', () => {
obj.set('location', newPoint); obj.set('location', newPoint);
return obj.save(); return obj.save();
}).then(() => { }).then(() => {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
return query.get(obj.id); return query.get(obj.id);
}).then((result) => { }).then((result) => {
const point = result.get('location'); const point = result.get('location');
@@ -48,8 +48,8 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('has the correct __type field in the json response', done => { it('has the correct __type field in the json response', done => {
var point = new Parse.GeoPoint(44.0, -11.0); const point = new Parse.GeoPoint(44.0, -11.0);
var obj = new TestObject(); const obj = new TestObject();
obj.set('location', point); obj.set('location', point);
obj.set('name', 'Zhoul') obj.set('name', 'Zhoul')
obj.save(null, { obj.save(null, {
@@ -69,8 +69,8 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('creating geo point exception two fields', (done) => { it('creating geo point exception two fields', (done) => {
var point = new Parse.GeoPoint(20, 20); const point = new Parse.GeoPoint(20, 20);
var obj = new TestObject(); const obj = new TestObject();
obj.set('locationOne', point); obj.set('locationOne', point);
obj.set('locationTwo', point); obj.set('locationTwo', point);
obj.save().then(() => { obj.save().then(() => {
@@ -83,8 +83,8 @@ describe('Parse.GeoPoint testing', () => {
// TODO: This should also have support in postgres, or higher level database agnostic support. // TODO: This should also have support in postgres, or higher level database agnostic support.
it_exclude_dbs(['postgres'])('updating geo point exception two fields', (done) => { it_exclude_dbs(['postgres'])('updating geo point exception two fields', (done) => {
var point = new Parse.GeoPoint(20, 20); const point = new Parse.GeoPoint(20, 20);
var obj = new TestObject(); const obj = new TestObject();
obj.set('locationOne', point); obj.set('locationOne', point);
obj.save(null, { obj.save(null, {
success: (obj) => { success: (obj) => {
@@ -100,10 +100,10 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('geo line', (done) => { it('geo line', (done) => {
var line = []; const line = [];
for (var i = 0; i < 10; ++i) { for (let i = 0; i < 10; ++i) {
var obj = new TestObject(); const obj = new TestObject();
var point = new Parse.GeoPoint(i * 4.0 - 12.0, i * 3.2 - 11.0); const point = new Parse.GeoPoint(i * 4.0 - 12.0, i * 3.2 - 11.0);
obj.set('location', point); obj.set('location', point);
obj.set('construct', 'line'); obj.set('construct', 'line');
obj.set('seq', i); obj.set('seq', i);
@@ -111,8 +111,8 @@ describe('Parse.GeoPoint testing', () => {
} }
Parse.Object.saveAll(line, { Parse.Object.saveAll(line, {
success: function() { success: function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
var point = new Parse.GeoPoint(24, 19); const point = new Parse.GeoPoint(24, 19);
query.equalTo('construct', 'line'); query.equalTo('construct', 'line');
query.withinMiles('location', point, 10000); query.withinMiles('location', point, 10000);
query.find({ query.find({
@@ -128,17 +128,17 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('geo max distance large', (done) => { it('geo max distance large', (done) => {
var objects = []; const objects = [];
[0, 1, 2].map(function(i) { [0, 1, 2].map(function(i) {
var obj = new TestObject(); const obj = new TestObject();
var point = new Parse.GeoPoint(0.0, i * 45.0); const point = new Parse.GeoPoint(0.0, i * 45.0);
obj.set('location', point); obj.set('location', point);
obj.set('index', i); obj.set('index', i);
objects.push(obj); objects.push(obj);
}); });
Parse.Object.saveAll(objects).then(() => { Parse.Object.saveAll(objects).then(() => {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
var point = new Parse.GeoPoint(1.0, -1.0); const point = new Parse.GeoPoint(1.0, -1.0);
query.withinRadians('location', point, 3.14); query.withinRadians('location', point, 3.14);
return query.find(); return query.find();
}).then((results) => { }).then((results) => {
@@ -151,17 +151,17 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('geo max distance medium', (done) => { it('geo max distance medium', (done) => {
var objects = []; const objects = [];
[0, 1, 2].map(function(i) { [0, 1, 2].map(function(i) {
var obj = new TestObject(); const obj = new TestObject();
var point = new Parse.GeoPoint(0.0, i * 45.0); const point = new Parse.GeoPoint(0.0, i * 45.0);
obj.set('location', point); obj.set('location', point);
obj.set('index', i); obj.set('index', i);
objects.push(obj); objects.push(obj);
}); });
Parse.Object.saveAll(objects, function() { Parse.Object.saveAll(objects, function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
var point = new Parse.GeoPoint(1.0, -1.0); const point = new Parse.GeoPoint(1.0, -1.0);
query.withinRadians('location', point, 3.14 * 0.5); query.withinRadians('location', point, 3.14 * 0.5);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -175,17 +175,17 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('geo max distance small', (done) => { it('geo max distance small', (done) => {
var objects = []; const objects = [];
[0, 1, 2].map(function(i) { [0, 1, 2].map(function(i) {
var obj = new TestObject(); const obj = new TestObject();
var point = new Parse.GeoPoint(0.0, i * 45.0); const point = new Parse.GeoPoint(0.0, i * 45.0);
obj.set('location', point); obj.set('location', point);
obj.set('index', i); obj.set('index', i);
objects.push(obj); objects.push(obj);
}); });
Parse.Object.saveAll(objects, function() { Parse.Object.saveAll(objects, function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
var point = new Parse.GeoPoint(1.0, -1.0); const point = new Parse.GeoPoint(1.0, -1.0);
query.withinRadians('location', point, 3.14 * 0.25); query.withinRadians('location', point, 3.14 * 0.25);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -197,16 +197,16 @@ describe('Parse.GeoPoint testing', () => {
}); });
}); });
var makeSomeGeoPoints = function(callback) { const makeSomeGeoPoints = function(callback) {
var sacramento = new TestObject(); const sacramento = new TestObject();
sacramento.set('location', new Parse.GeoPoint(38.52, -121.50)); sacramento.set('location', new Parse.GeoPoint(38.52, -121.50));
sacramento.set('name', 'Sacramento'); sacramento.set('name', 'Sacramento');
var honolulu = new TestObject(); const honolulu = new TestObject();
honolulu.set('location', new Parse.GeoPoint(21.35, -157.93)); honolulu.set('location', new Parse.GeoPoint(21.35, -157.93));
honolulu.set('name', 'Honolulu'); honolulu.set('name', 'Honolulu');
var sf = new TestObject(); const sf = new TestObject();
sf.set('location', new Parse.GeoPoint(37.75, -122.68)); sf.set('location', new Parse.GeoPoint(37.75, -122.68));
sf.set('name', 'San Francisco'); sf.set('name', 'San Francisco');
@@ -215,8 +215,8 @@ describe('Parse.GeoPoint testing', () => {
it('geo max distance in km everywhere', (done) => { it('geo max distance in km everywhere', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
// Honolulu is 4300 km away from SFO on a sphere ;) // Honolulu is 4300 km away from SFO on a sphere ;)
query.withinKilometers('location', sfo, 4800.0); query.withinKilometers('location', sfo, 4800.0);
query.find({ query.find({
@@ -230,8 +230,8 @@ describe('Parse.GeoPoint testing', () => {
it('geo max distance in km california', (done) => { it('geo max distance in km california', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 3700.0); query.withinKilometers('location', sfo, 3700.0);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -246,8 +246,8 @@ describe('Parse.GeoPoint testing', () => {
it('geo max distance in km bay area', (done) => { it('geo max distance in km bay area', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 100.0); query.withinKilometers('location', sfo, 100.0);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -261,8 +261,8 @@ describe('Parse.GeoPoint testing', () => {
it('geo max distance in km mid peninsula', (done) => { it('geo max distance in km mid peninsula', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 10.0); query.withinKilometers('location', sfo, 10.0);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -275,8 +275,8 @@ describe('Parse.GeoPoint testing', () => {
it('geo max distance in miles everywhere', (done) => { it('geo max distance in miles everywhere', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 2600.0); query.withinMiles('location', sfo, 2600.0);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -289,8 +289,8 @@ describe('Parse.GeoPoint testing', () => {
it('geo max distance in miles california', (done) => { it('geo max distance in miles california', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 2200.0); query.withinMiles('location', sfo, 2200.0);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -305,8 +305,8 @@ describe('Parse.GeoPoint testing', () => {
it('geo max distance in miles bay area', (done) => { it('geo max distance in miles bay area', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
// 100km is 62 miles... // 100km is 62 miles...
query.withinMiles('location', sfo, 62.0); query.withinMiles('location', sfo, 62.0);
query.find({ query.find({
@@ -321,8 +321,8 @@ describe('Parse.GeoPoint testing', () => {
it('geo max distance in miles mid peninsula', (done) => { it('geo max distance in miles mid peninsula', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 10.0); query.withinMiles('location', sfo, 10.0);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -335,8 +335,8 @@ describe('Parse.GeoPoint testing', () => {
it('returns nearest location', (done) => { it('returns nearest location', (done) => {
makeSomeGeoPoints(function() { makeSomeGeoPoints(function() {
var sfo = new Parse.GeoPoint(37.6189722, -122.3748889); const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.near('location', sfo); query.near('location', sfo);
query.find({ query.find({
success: function(results) { success: function(results) {
@@ -368,16 +368,16 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('supports a sub-object with a geo point', done => { it('supports a sub-object with a geo point', done => {
var point = new Parse.GeoPoint(44.0, -11.0); const point = new Parse.GeoPoint(44.0, -11.0);
var obj = new TestObject(); const obj = new TestObject();
obj.set('subobject', { location: point }); obj.set('subobject', { location: point });
obj.save(null, { obj.save(null, {
success: function() { success: function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 1); equal(results.length, 1);
var pointAgain = results[0].get('subobject')['location']; const pointAgain = results[0].get('subobject')['location'];
ok(pointAgain); ok(pointAgain);
equal(pointAgain.latitude, 44.0); equal(pointAgain.latitude, 44.0);
equal(pointAgain.longitude, -11.0); equal(pointAgain.longitude, -11.0);
@@ -389,17 +389,17 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('supports array of geo points', done => { it('supports array of geo points', done => {
var point1 = new Parse.GeoPoint(44.0, -11.0); const point1 = new Parse.GeoPoint(44.0, -11.0);
var point2 = new Parse.GeoPoint(22.0, -55.0); const point2 = new Parse.GeoPoint(22.0, -55.0);
var obj = new TestObject(); const obj = new TestObject();
obj.set('locations', [ point1, point2 ]); obj.set('locations', [ point1, point2 ]);
obj.save(null, { obj.save(null, {
success: function() { success: function() {
var query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);
query.find({ query.find({
success: function(results) { success: function(results) {
equal(results.length, 1); equal(results.length, 1);
var locations = results[0].get('locations'); const locations = results[0].get('locations');
expect(locations.length).toEqual(2); expect(locations.length).toEqual(2);
expect(locations[0]).toEqual(point1); expect(locations[0]).toEqual(point1);
expect(locations[1]).toEqual(point2); expect(locations[1]).toEqual(point2);
@@ -411,8 +411,8 @@ describe('Parse.GeoPoint testing', () => {
}); });
it('equalTo geopoint', (done) => { it('equalTo geopoint', (done) => {
var point = new Parse.GeoPoint(44.0, -11.0); const point = new Parse.GeoPoint(44.0, -11.0);
var obj = new TestObject(); const obj = new TestObject();
obj.set('location', point); obj.set('location', point);
obj.save().then(() => { obj.save().then(() => {
const query = new Parse.Query(TestObject); const query = new Parse.Query(TestObject);

View File

@@ -1,6 +1,6 @@
'use strict'; 'use strict';
var request = require('request'); const request = require('request');
const Config = require('../src/Config'); const Config = require('../src/Config');
describe('a GlobalConfig', () => { describe('a GlobalConfig', () => {

View File

@@ -1,16 +1,16 @@
"use strict"; "use strict";
/* global describe, it, expect, fail, Parse */ /* global describe, it, expect, fail, Parse */
var request = require('request'); const request = require('request');
var triggers = require('../src/triggers'); const triggers = require('../src/triggers');
var HooksController = require('../src/Controllers/HooksController').default; const HooksController = require('../src/Controllers/HooksController').default;
var express = require("express"); const express = require("express");
var bodyParser = require('body-parser'); const bodyParser = require('body-parser');
var port = 12345; const port = 12345;
var hookServerURL = "http://localhost:" + port; const hookServerURL = "http://localhost:" + port;
const AppCache = require('../src/cache').AppCache; const AppCache = require('../src/cache').AppCache;
var app = express(); const app = express();
app.use(bodyParser.json({ 'type': '*/*' })) app.use(bodyParser.json({ 'type': '*/*' }))
app.listen(12345); app.listen(12345);
@@ -273,14 +273,14 @@ describe('Hooks', () => {
it("should create hooks and properly preload them", (done) => { it("should create hooks and properly preload them", (done) => {
var promises = []; const promises = [];
for (var i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
promises.push(Parse.Hooks.createTrigger("MyClass" + i, "beforeSave", "http://url.com/beforeSave/" + i)); promises.push(Parse.Hooks.createTrigger("MyClass" + i, "beforeSave", "http://url.com/beforeSave/" + i));
promises.push(Parse.Hooks.createFunction("AFunction" + i, "http://url.com/function" + i)); promises.push(Parse.Hooks.createFunction("AFunction" + i, "http://url.com/function" + i));
} }
Parse.Promise.when(promises).then(function(){ Parse.Promise.when(promises).then(function(){
for (var i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
// Delete everything from memory, as the server just started // Delete everything from memory, as the server just started
triggers.removeTrigger("beforeSave", "MyClass" + i, Parse.applicationId); triggers.removeTrigger("beforeSave", "MyClass" + i, Parse.applicationId);
triggers.removeFunction("AFunction" + i, Parse.applicationId); triggers.removeFunction("AFunction" + i, Parse.applicationId);
@@ -294,7 +294,7 @@ describe('Hooks', () => {
fail('Should properly create all hooks'); fail('Should properly create all hooks');
done(); done();
}).then(function() { }).then(function() {
for (var i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
expect(triggers.getTrigger("MyClass" + i, "beforeSave", Parse.applicationId)).not.toBeUndefined(); expect(triggers.getTrigger("MyClass" + i, "beforeSave", Parse.applicationId)).not.toBeUndefined();
expect(triggers.getFunction("AFunction" + i, Parse.applicationId)).not.toBeUndefined(); expect(triggers.getFunction("AFunction" + i, Parse.applicationId)).not.toBeUndefined();
} }
@@ -414,10 +414,10 @@ describe('Hooks', () => {
it("should run the beforeSave hook on the test server", (done) => { it("should run the beforeSave hook on the test server", (done) => {
var triggerCount = 0; let triggerCount = 0;
app.post("/BeforeSaveSome", function(req, res) { app.post("/BeforeSaveSome", function(req, res) {
triggerCount++; triggerCount++;
var object = req.body.object; const object = req.body.object;
object.hello = "world"; object.hello = "world";
// Would need parse cloud express to set much more // Would need parse cloud express to set much more
// But this should override the key upon return // But this should override the key upon return
@@ -442,7 +442,7 @@ describe('Hooks', () => {
it("beforeSave hooks should correctly handle responses containing entire object", (done) => { it("beforeSave hooks should correctly handle responses containing entire object", (done) => {
app.post("/BeforeSaveSome2", function(req, res) { app.post("/BeforeSaveSome2", function(req, res) {
var object = Parse.Object.fromJSON(req.body.object); const object = Parse.Object.fromJSON(req.body.object);
object.set('hello', "world"); object.set('hello', "world");
res.json({success: object}); res.json({success: object});
}); });
@@ -461,11 +461,11 @@ describe('Hooks', () => {
}); });
it("should run the afterSave hook on the test server", (done) => { it("should run the afterSave hook on the test server", (done) => {
var triggerCount = 0; let triggerCount = 0;
var newObjectId; let newObjectId;
app.post("/AfterSaveSome", function(req, res) { app.post("/AfterSaveSome", function(req, res) {
triggerCount++; triggerCount++;
var obj = new Parse.Object("AnotherObject"); const obj = new Parse.Object("AnotherObject");
obj.set("foo", "bar"); obj.set("foo", "bar");
obj.save().then(function(obj){ obj.save().then(function(obj){
newObjectId = obj.id; newObjectId = obj.id;
@@ -477,7 +477,7 @@ describe('Hooks', () => {
const obj = new Parse.Object("SomeRandomObject"); const obj = new Parse.Object("SomeRandomObject");
return obj.save(); return obj.save();
}).then(function() { }).then(function() {
var promise = new Parse.Promise(); const promise = new Parse.Promise();
// Wait a bit here as it's an after save // Wait a bit here as it's an after save
setTimeout(() => { setTimeout(() => {
expect(triggerCount).toBe(1); expect(triggerCount).toBe(1);

View File

@@ -26,9 +26,9 @@ describe('Installations', () => {
}); });
it('creates an android installation with ids', (done) => { it('creates an android installation with ids', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var device = 'android'; const device = 'android';
var input = { const input = {
'installationId': installId, 'installationId': installId,
'deviceType': device 'deviceType': device
}; };
@@ -36,7 +36,7 @@ describe('Installations', () => {
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(obj.installationId).toEqual(installId); expect(obj.installationId).toEqual(installId);
expect(obj.deviceType).toEqual(device); expect(obj.deviceType).toEqual(device);
done(); done();
@@ -44,9 +44,9 @@ describe('Installations', () => {
}); });
it('creates an ios installation with ids', (done) => { it('creates an ios installation with ids', (done) => {
var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
var device = 'ios'; const device = 'ios';
var input = { const input = {
'deviceToken': t, 'deviceToken': t,
'deviceType': device 'deviceType': device
}; };
@@ -54,7 +54,7 @@ describe('Installations', () => {
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(obj.deviceToken).toEqual(t); expect(obj.deviceToken).toEqual(t);
expect(obj.deviceType).toEqual(device); expect(obj.deviceType).toEqual(device);
done(); done();
@@ -62,9 +62,9 @@ describe('Installations', () => {
}); });
it('creates an embedded installation with ids', (done) => { it('creates an embedded installation with ids', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var device = 'embedded'; const device = 'embedded';
var input = { const input = {
'installationId': installId, 'installationId': installId,
'deviceType': device 'deviceType': device
}; };
@@ -72,7 +72,7 @@ describe('Installations', () => {
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(obj.installationId).toEqual(installId); expect(obj.installationId).toEqual(installId);
expect(obj.deviceType).toEqual(device); expect(obj.deviceType).toEqual(device);
done(); done();
@@ -80,9 +80,9 @@ describe('Installations', () => {
}); });
it('creates an android installation with all fields', (done) => { it('creates an android installation with all fields', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var device = 'android'; const device = 'android';
var input = { const input = {
'installationId': installId, 'installationId': installId,
'deviceType': device, 'deviceType': device,
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
@@ -91,7 +91,7 @@ describe('Installations', () => {
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(obj.installationId).toEqual(installId); expect(obj.installationId).toEqual(installId);
expect(obj.deviceType).toEqual(device); expect(obj.deviceType).toEqual(device);
expect(typeof obj.channels).toEqual('object'); expect(typeof obj.channels).toEqual('object');
@@ -103,9 +103,9 @@ describe('Installations', () => {
}); });
it('creates an ios installation with all fields', (done) => { it('creates an ios installation with all fields', (done) => {
var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
var device = 'ios'; const device = 'ios';
var input = { const input = {
'deviceToken': t, 'deviceToken': t,
'deviceType': device, 'deviceType': device,
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
@@ -114,7 +114,7 @@ describe('Installations', () => {
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(obj.deviceToken).toEqual(t); expect(obj.deviceToken).toEqual(t);
expect(obj.deviceType).toEqual(device); expect(obj.deviceType).toEqual(device);
expect(typeof obj.channels).toEqual('object'); expect(typeof obj.channels).toEqual('object');
@@ -126,9 +126,9 @@ describe('Installations', () => {
}); });
it('should properly fail queying installations', (done) => { it('should properly fail queying installations', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var device = 'android'; const device = 'android';
var input = { const input = {
'installationId': installId, 'installationId': installId,
'deviceType': device 'deviceType': device
}; };
@@ -147,9 +147,9 @@ describe('Installations', () => {
}); });
it('should properly queying installations with masterKey', (done) => { it('should properly queying installations with masterKey', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var device = 'android'; const device = 'android';
var input = { const input = {
'installationId': installId, 'installationId': installId,
'deviceType': device 'deviceType': device
}; };
@@ -159,7 +159,7 @@ describe('Installations', () => {
return query.find({useMasterKey: true}); return query.find({useMasterKey: true});
}).then((results) => { }).then((results) => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0].toJSON(); const obj = results[0].toJSON();
expect(obj.installationId).toEqual(installId); expect(obj.installationId).toEqual(installId);
expect(obj.deviceType).toEqual(device); expect(obj.deviceType).toEqual(device);
done(); done();
@@ -170,7 +170,7 @@ describe('Installations', () => {
}); });
it('fails with missing ids', (done) => { it('fails with missing ids', (done) => {
var input = { const input = {
'deviceType': 'android', 'deviceType': 'android',
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
}; };
@@ -185,8 +185,8 @@ describe('Installations', () => {
}); });
it('fails for android with missing type', (done) => { it('fails for android with missing type', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var input = { const input = {
'installationId': installId, 'installationId': installId,
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
}; };
@@ -201,8 +201,8 @@ describe('Installations', () => {
}); });
it('creates an object with custom fields', (done) => { it('creates an object with custom fields', (done) => {
var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
var input = { const input = {
'deviceToken': t, 'deviceToken': t,
'deviceType': 'ios', 'deviceType': 'ios',
'channels': ['foo', 'bar'], 'channels': ['foo', 'bar'],
@@ -212,7 +212,7 @@ describe('Installations', () => {
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(obj.custom).toEqual('allowed'); expect(obj.custom).toEqual('allowed');
done(); done();
}).catch((error) => { console.log(error); }); }).catch((error) => { console.log(error); });
@@ -221,16 +221,16 @@ describe('Installations', () => {
// Note: did not port test 'TestObjectIDForIdentifiers' // Note: did not port test 'TestObjectIDForIdentifiers'
it('merging when installationId already exists', (done) => { it('merging when installationId already exists', (done) => {
var installId1 = '12345678-abcd-abcd-abcd-123456789abc'; const installId1 = '12345678-abcd-abcd-abcd-123456789abc';
var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
var input = { const input = {
'deviceToken': t, 'deviceToken': t,
'deviceType': 'ios', 'deviceType': 'ios',
'installationId': installId1, 'installationId': installId1,
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
}; };
var firstObject; let firstObject;
var secondObject; let secondObject;
rest.create(config, auth.nobody(config), '_Installation', input) rest.create(config, auth.nobody(config), '_Installation', input)
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
@@ -253,23 +253,23 @@ describe('Installations', () => {
}); });
it('merging when two objects both only have one id', (done) => { it('merging when two objects both only have one id', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input1 = { const input1 = {
'installationId': installId, 'installationId': installId,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var input2 = { const input2 = {
'deviceToken': t, 'deviceToken': t,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var input3 = { const input3 = {
'deviceToken': t, 'deviceToken': t,
'installationId': installId, 'installationId': installId,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var firstObject; let firstObject;
var secondObject; let secondObject;
rest.create(config, auth.nobody(config), '_Installation', input1) rest.create(config, auth.nobody(config), '_Installation', input1)
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
@@ -299,11 +299,11 @@ describe('Installations', () => {
}); });
xit('creating multiple devices with same device token works', (done) => { xit('creating multiple devices with same device token works', (done) => {
var installId1 = '11111111-abcd-abcd-abcd-123456789abc'; const installId1 = '11111111-abcd-abcd-abcd-123456789abc';
var installId2 = '22222222-abcd-abcd-abcd-123456789abc'; const installId2 = '22222222-abcd-abcd-abcd-123456789abc';
var installId3 = '33333333-abcd-abcd-abcd-123456789abc'; const installId3 = '33333333-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { const input = {
'installationId': installId1, 'installationId': installId1,
'deviceType': 'ios', 'deviceType': 'ios',
'deviceToken': t 'deviceToken': t
@@ -330,7 +330,7 @@ describe('Installations', () => {
}); });
it('updating with new channels', (done) => { it('updating with new channels', (done) => {
var input = { const input = {
installationId: '12345678-abcd-abcd-abcd-123456789abc', installationId: '12345678-abcd-abcd-abcd-123456789abc',
deviceType: 'android', deviceType: 'android',
channels: ['foo', 'bar'] channels: ['foo', 'bar']
@@ -339,8 +339,8 @@ describe('Installations', () => {
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var objectId = results[0].objectId; const objectId = results[0].objectId;
var update = { const update = {
'channels': ['baz'] 'channels': ['baz']
}; };
return rest.update(config, auth.nobody(config), '_Installation', { objectId }, update); return rest.update(config, auth.nobody(config), '_Installation', { objectId }, update);
@@ -358,9 +358,9 @@ describe('Installations', () => {
}); });
it('update android fails with new installation id', (done) => { it('update android fails with new installation id', (done) => {
var installId1 = '12345678-abcd-abcd-abcd-123456789abc'; const installId1 = '12345678-abcd-abcd-abcd-123456789abc';
var installId2 = '87654321-abcd-abcd-abcd-123456789abc'; const installId2 = '87654321-abcd-abcd-abcd-123456789abc';
var input = { let input = {
'installationId': installId1, 'installationId': installId1,
'deviceType': 'android', 'deviceType': 'android',
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
@@ -381,9 +381,9 @@ describe('Installations', () => {
}); });
it('update ios fails with new deviceToken and no installationId', (done) => { it('update ios fails with new deviceToken and no installationId', (done) => {
var a = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const a = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
var b = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const b = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
var input = { let input = {
'deviceToken': a, 'deviceToken': a,
'deviceType': 'ios', 'deviceType': 'ios',
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
@@ -403,10 +403,10 @@ describe('Installations', () => {
}); });
it('update ios updates device token', (done) => { it('update ios updates device token', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
var u = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const u = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306';
var input = { let input = {
'installationId': installId, 'installationId': installId,
'deviceType': 'ios', 'deviceType': 'ios',
'deviceToken': t, 'deviceToken': t,
@@ -435,8 +435,8 @@ describe('Installations', () => {
}); });
it('update fails to change deviceType', (done) => { it('update fails to change deviceType', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var input = { let input = {
'installationId': installId, 'installationId': installId,
'deviceType': 'android', 'deviceType': 'android',
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
@@ -459,8 +459,8 @@ describe('Installations', () => {
}); });
it('update android with custom field', (done) => { it('update android with custom field', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var input = { let input = {
'installationId': installId, 'installationId': installId,
'deviceType': 'android', 'deviceType': 'android',
'channels': ['foo', 'bar'] 'channels': ['foo', 'bar']
@@ -483,16 +483,16 @@ describe('Installations', () => {
}); });
it('update android device token with duplicate device token', (done) => { it('update android device token with duplicate device token', (done) => {
var installId1 = '11111111-abcd-abcd-abcd-123456789abc'; const installId1 = '11111111-abcd-abcd-abcd-123456789abc';
var installId2 = '22222222-abcd-abcd-abcd-123456789abc'; const installId2 = '22222222-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { let input = {
'installationId': installId1, 'installationId': installId1,
'deviceToken': t, 'deviceToken': t,
'deviceType': 'android' 'deviceType': 'android'
}; };
var firstObject; let firstObject;
var secondObject; let secondObject;
rest.create(config, auth.nobody(config), '_Installation', input) rest.create(config, auth.nobody(config), '_Installation', input)
.then(() => { .then(() => {
input = { input = {
@@ -528,16 +528,16 @@ describe('Installations', () => {
}); });
it('update ios device token with duplicate device token', (done) => { it('update ios device token with duplicate device token', (done) => {
var installId1 = '11111111-abcd-abcd-abcd-123456789abc'; const installId1 = '11111111-abcd-abcd-abcd-123456789abc';
var installId2 = '22222222-abcd-abcd-abcd-123456789abc'; const installId2 = '22222222-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { let input = {
'installationId': installId1, 'installationId': installId1,
'deviceToken': t, 'deviceToken': t,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var firstObject; let firstObject;
var secondObject; let secondObject;
rest.create(config, auth.nobody(config), '_Installation', input) rest.create(config, auth.nobody(config), '_Installation', input)
.then(() => { .then(() => {
input = { input = {
@@ -577,10 +577,10 @@ describe('Installations', () => {
}); });
xit('update ios device token with duplicate token different app', (done) => { xit('update ios device token with duplicate token different app', (done) => {
var installId1 = '11111111-abcd-abcd-abcd-123456789abc'; const installId1 = '11111111-abcd-abcd-abcd-123456789abc';
var installId2 = '22222222-abcd-abcd-abcd-123456789abc'; const installId2 = '22222222-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { const input = {
'installationId': installId1, 'installationId': installId1,
'deviceToken': t, 'deviceToken': t,
'deviceType': 'ios', 'deviceType': 'ios',
@@ -605,9 +605,9 @@ describe('Installations', () => {
}); });
it('update ios token and channels', (done) => { it('update ios token and channels', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { let input = {
'installationId': installId, 'installationId': installId,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
@@ -635,9 +635,9 @@ describe('Installations', () => {
}); });
it('update ios linking two existing objects', (done) => { it('update ios linking two existing objects', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { let input = {
'installationId': installId, 'installationId': installId,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
@@ -673,9 +673,9 @@ describe('Installations', () => {
}); });
it('update is linking two existing objects w/ increment', (done) => { it('update is linking two existing objects w/ increment', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { let input = {
'installationId': installId, 'installationId': installId,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
@@ -716,14 +716,14 @@ describe('Installations', () => {
}); });
it('update is linking two existing with installation id', (done) => { it('update is linking two existing with installation id', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { let input = {
'installationId': installId, 'installationId': installId,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var installObj; let installObj;
var tokenObj; let tokenObj;
rest.create(config, auth.nobody(config), '_Installation', input) rest.create(config, auth.nobody(config), '_Installation', input)
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
@@ -759,14 +759,14 @@ describe('Installations', () => {
}); });
it('update is linking two existing with installation id w/ op', (done) => { it('update is linking two existing with installation id w/ op', (done) => {
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var input = { let input = {
'installationId': installId, 'installationId': installId,
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var installObj; let installObj;
var tokenObj; let tokenObj;
rest.create(config, auth.nobody(config), '_Installation', input) rest.create(config, auth.nobody(config), '_Installation', input)
.then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(() => database.adapter.find('_Installation', installationSchema, {}, {}))
.then(results => { .then(results => {
@@ -817,9 +817,9 @@ describe('Installations', () => {
// imported installation, then we should reuse the existing installation // imported installation, then we should reuse the existing installation
// object in case the developer already added additional fields via Data // object in case the developer already added additional fields via Data
// Browser or REST API (e.g. channel targeting info). // Browser or REST API (e.g. channel targeting info).
var t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
var installId = '12345678-abcd-abcd-abcd-123456789abc'; const installId = '12345678-abcd-abcd-abcd-123456789abc';
var input = { let input = {
'deviceToken': t, 'deviceToken': t,
'deviceType': 'ios' 'deviceType': 'ios'
}; };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -180,7 +180,7 @@ describe('Parse.Polygon testing', () => {
'X-Parse-Javascript-Key': Parse.javaScriptKey 'X-Parse-Javascript-Key': Parse.javaScriptKey
} }
}); });
}).then(done.fail, done); }).then(done.fail, () => done());
}); });
it('polygonContain invalid geoPoint', (done) => { it('polygonContain invalid geoPoint', (done) => {
@@ -203,7 +203,7 @@ describe('Parse.Polygon testing', () => {
'X-Parse-Javascript-Key': Parse.javaScriptKey 'X-Parse-Javascript-Key': Parse.javaScriptKey
} }
}); });
}).then(done.fail, done); }).then(done.fail, () => done());
}); });
}); });

View File

@@ -1,16 +1,16 @@
var ParsePubSub = require('../src/LiveQuery/ParsePubSub').ParsePubSub; const ParsePubSub = require('../src/LiveQuery/ParsePubSub').ParsePubSub;
describe('ParsePubSub', function() { describe('ParsePubSub', function() {
beforeEach(function(done) { beforeEach(function(done) {
// Mock RedisPubSub // Mock RedisPubSub
var mockRedisPubSub = { const mockRedisPubSub = {
createPublisher: jasmine.createSpy('createPublisherRedis'), createPublisher: jasmine.createSpy('createPublisherRedis'),
createSubscriber: jasmine.createSpy('createSubscriberRedis') createSubscriber: jasmine.createSpy('createSubscriberRedis')
}; };
jasmine.mockLibrary('../src/Adapters/PubSub/RedisPubSub', 'RedisPubSub', mockRedisPubSub); jasmine.mockLibrary('../src/Adapters/PubSub/RedisPubSub', 'RedisPubSub', mockRedisPubSub);
// Mock EventEmitterPubSub // Mock EventEmitterPubSub
var mockEventEmitterPubSub = { const mockEventEmitterPubSub = {
createPublisher: jasmine.createSpy('createPublisherEventEmitter'), createPublisher: jasmine.createSpy('createPublisherEventEmitter'),
createSubscriber: jasmine.createSpy('createSubscriberEventEmitter') createSubscriber: jasmine.createSpy('createSubscriberEventEmitter')
}; };
@@ -23,8 +23,8 @@ describe('ParsePubSub', function() {
redisURL: 'redisURL' redisURL: 'redisURL'
}); });
var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub;
var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub;
expect(RedisPubSub.createPublisher).toHaveBeenCalledWith({redisURL: 'redisURL'}); expect(RedisPubSub.createPublisher).toHaveBeenCalledWith({redisURL: 'redisURL'});
expect(EventEmitterPubSub.createPublisher).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createPublisher).not.toHaveBeenCalled();
}); });
@@ -32,8 +32,8 @@ describe('ParsePubSub', function() {
it('can create event emitter publisher', function() { it('can create event emitter publisher', function() {
ParsePubSub.createPublisher({}); ParsePubSub.createPublisher({});
var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub;
var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub;
expect(RedisPubSub.createPublisher).not.toHaveBeenCalled(); expect(RedisPubSub.createPublisher).not.toHaveBeenCalled();
expect(EventEmitterPubSub.createPublisher).toHaveBeenCalled(); expect(EventEmitterPubSub.createPublisher).toHaveBeenCalled();
}); });
@@ -43,8 +43,8 @@ describe('ParsePubSub', function() {
redisURL: 'redisURL' redisURL: 'redisURL'
}); });
var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub;
var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub;
expect(RedisPubSub.createSubscriber).toHaveBeenCalledWith({redisURL: 'redisURL'}); expect(RedisPubSub.createSubscriber).toHaveBeenCalledWith({redisURL: 'redisURL'});
expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled();
}); });
@@ -52,8 +52,8 @@ describe('ParsePubSub', function() {
it('can create event emitter subscriber', function() { it('can create event emitter subscriber', function() {
ParsePubSub.createSubscriber({}); ParsePubSub.createSubscriber({});
var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub;
var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub;
expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled();
expect(EventEmitterPubSub.createSubscriber).toHaveBeenCalled(); expect(EventEmitterPubSub.createSubscriber).toHaveBeenCalled();
}); });
@@ -73,8 +73,8 @@ describe('ParsePubSub', function() {
}); });
expect(adapter.createSubscriber).toHaveBeenCalled(); expect(adapter.createSubscriber).toHaveBeenCalled();
var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub;
var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub;
expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled();
expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled();
expect(RedisPubSub.createPublisher).not.toHaveBeenCalled(); expect(RedisPubSub.createPublisher).not.toHaveBeenCalled();
@@ -100,8 +100,8 @@ describe('ParsePubSub', function() {
}); });
expect(adapter.createSubscriber).toHaveBeenCalled(); expect(adapter.createSubscriber).toHaveBeenCalled();
var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub;
var EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; const EventEmitterPubSub = require('../src/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub;
expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled();
expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled();
expect(RedisPubSub.createPublisher).not.toHaveBeenCalled(); expect(RedisPubSub.createPublisher).not.toHaveBeenCalled();

File diff suppressed because it is too large Load Diff

View File

@@ -2,16 +2,16 @@
// This is a port of the test suite: // This is a port of the test suite:
// hungry/js/test/parse_relation_test.js // hungry/js/test/parse_relation_test.js
var ChildObject = Parse.Object.extend({className: "ChildObject"}); const ChildObject = Parse.Object.extend({className: "ChildObject"});
var ParentObject = Parse.Object.extend({className: "ParentObject"}); const ParentObject = Parse.Object.extend({className: "ParentObject"});
describe('Parse.Relation testing', () => { describe('Parse.Relation testing', () => {
it("simple add and remove relation", (done) => { it("simple add and remove relation", (done) => {
var child = new ChildObject(); const child = new ChildObject();
child.set("x", 2); child.set("x", 2);
var parent = new ParentObject(); const parent = new ParentObject();
parent.set("x", 4); parent.set("x", 4);
var relation = parent.relation("child"); const relation = parent.relation("child");
child.save().then(() => { child.save().then(() => {
relation.add(child); relation.add(child);
@@ -42,24 +42,24 @@ describe('Parse.Relation testing', () => {
}); });
it("query relation without schema", (done) => { it("query relation without schema", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x:i})); childObjects.push(new ChildObject({x:i}));
} }
Parse.Object.saveAll(childObjects, expectSuccess({ Parse.Object.saveAll(childObjects, expectSuccess({
success: function() { success: function() {
var ParentObject = Parse.Object.extend("ParentObject"); const ParentObject = Parse.Object.extend("ParentObject");
var parent = new ParentObject(); const parent = new ParentObject();
parent.set("x", 4); parent.set("x", 4);
var relation = parent.relation("child"); const relation = parent.relation("child");
relation.add(childObjects[0]); relation.add(childObjects[0]);
parent.save(null, expectSuccess({ parent.save(null, expectSuccess({
success: function() { success: function() {
var parentAgain = new ParentObject(); const parentAgain = new ParentObject();
parentAgain.id = parent.id; parentAgain.id = parent.id;
var relation = parentAgain.relation("child"); const relation = parentAgain.relation("child");
relation.query().find(expectSuccess({ relation.query().find(expectSuccess({
success: function(list) { success: function(list) {
equal(list.length, 1, equal(list.length, 1,
@@ -77,25 +77,25 @@ describe('Parse.Relation testing', () => {
it("relations are constructed right from query", (done) => { it("relations are constructed right from query", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i})); childObjects.push(new ChildObject({x: i}));
} }
Parse.Object.saveAll(childObjects, { Parse.Object.saveAll(childObjects, {
success: function() { success: function() {
var ParentObject = Parse.Object.extend("ParentObject"); const ParentObject = Parse.Object.extend("ParentObject");
var parent = new ParentObject(); const parent = new ParentObject();
parent.set("x", 4); parent.set("x", 4);
var relation = parent.relation("child"); const relation = parent.relation("child");
relation.add(childObjects[0]); relation.add(childObjects[0]);
parent.save(null, { parent.save(null, {
success: function() { success: function() {
var query = new Parse.Query(ParentObject); const query = new Parse.Query(ParentObject);
query.get(parent.id, { query.get(parent.id, {
success: function(object) { success: function(object) {
var relationAgain = object.relation("child"); const relationAgain = object.relation("child");
relationAgain.query().find({ relationAgain.query().find({
success: function(list) { success: function(list) {
equal(list.length, 1, equal(list.length, 1,
@@ -122,17 +122,17 @@ describe('Parse.Relation testing', () => {
}); });
it("compound add and remove relation", (done) => { it("compound add and remove relation", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i})); childObjects.push(new ChildObject({x: i}));
} }
var parent; let parent;
var relation; let relation;
Parse.Object.saveAll(childObjects).then(function() { Parse.Object.saveAll(childObjects).then(function() {
var ParentObject = Parse.Object.extend('ParentObject'); const ParentObject = Parse.Object.extend('ParentObject');
parent = new ParentObject(); parent = new ParentObject();
parent.set('x', 4); parent.set('x', 4);
relation = parent.relation('child'); relation = parent.relation('child');
@@ -164,17 +164,17 @@ describe('Parse.Relation testing', () => {
}); });
it("related at ordering optimizations", (done) => { it("related at ordering optimizations", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i})); childObjects.push(new ChildObject({x: i}));
} }
var parent; let parent;
var relation; let relation;
Parse.Object.saveAll(childObjects).then(function() { Parse.Object.saveAll(childObjects).then(function() {
var ParentObject = Parse.Object.extend('ParentObject'); const ParentObject = Parse.Object.extend('ParentObject');
parent = new ParentObject(); parent = new ParentObject();
parent.set('x', 4); parent.set('x', 4);
relation = parent.relation('child'); relation = parent.relation('child');
@@ -193,24 +193,24 @@ describe('Parse.Relation testing', () => {
it_exclude_dbs(['postgres'])("queries with relations", (done) => { it_exclude_dbs(['postgres'])("queries with relations", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i})); childObjects.push(new ChildObject({x: i}));
} }
Parse.Object.saveAll(childObjects, { Parse.Object.saveAll(childObjects, {
success: function() { success: function() {
var ParentObject = Parse.Object.extend("ParentObject"); const ParentObject = Parse.Object.extend("ParentObject");
var parent = new ParentObject(); const parent = new ParentObject();
parent.set("x", 4); parent.set("x", 4);
var relation = parent.relation("child"); const relation = parent.relation("child");
relation.add(childObjects[0]); relation.add(childObjects[0]);
relation.add(childObjects[1]); relation.add(childObjects[1]);
relation.add(childObjects[2]); relation.add(childObjects[2]);
parent.save(null, { parent.save(null, {
success: function() { success: function() {
var query = relation.query(); const query = relation.query();
query.equalTo("x", 2); query.equalTo("x", 2);
query.find({ query.find({
success: function(list) { success: function(list) {
@@ -230,34 +230,34 @@ describe('Parse.Relation testing', () => {
}); });
it("queries on relation fields", (done) => { it("queries on relation fields", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i})); childObjects.push(new ChildObject({x: i}));
} }
Parse.Object.saveAll(childObjects, { Parse.Object.saveAll(childObjects, {
success: function() { success: function() {
var ParentObject = Parse.Object.extend("ParentObject"); const ParentObject = Parse.Object.extend("ParentObject");
var parent = new ParentObject(); const parent = new ParentObject();
parent.set("x", 4); parent.set("x", 4);
var relation = parent.relation("child"); const relation = parent.relation("child");
relation.add(childObjects[0]); relation.add(childObjects[0]);
relation.add(childObjects[1]); relation.add(childObjects[1]);
relation.add(childObjects[2]); relation.add(childObjects[2]);
var parent2 = new ParentObject(); const parent2 = new ParentObject();
parent2.set("x", 3); parent2.set("x", 3);
var relation2 = parent2.relation("child"); const relation2 = parent2.relation("child");
relation2.add(childObjects[4]); relation2.add(childObjects[4]);
relation2.add(childObjects[5]); relation2.add(childObjects[5]);
relation2.add(childObjects[6]); relation2.add(childObjects[6]);
var parents = []; const parents = [];
parents.push(parent); parents.push(parent);
parents.push(parent2); parents.push(parent2);
Parse.Object.saveAll(parents, { Parse.Object.saveAll(parents, {
success: function() { success: function() {
var query = new Parse.Query(ParentObject); const query = new Parse.Query(ParentObject);
var objects = []; const objects = [];
objects.push(childObjects[4]); objects.push(childObjects[4]);
objects.push(childObjects[9]); objects.push(childObjects[9]);
query.containedIn("child", objects); query.containedIn("child", objects);
@@ -324,32 +324,32 @@ describe('Parse.Relation testing', () => {
}); });
it_exclude_dbs(['postgres'])("query on pointer and relation fields with equal", (done) => { it_exclude_dbs(['postgres'])("query on pointer and relation fields with equal", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i})); childObjects.push(new ChildObject({x: i}));
} }
Parse.Object.saveAll(childObjects).then(() => { Parse.Object.saveAll(childObjects).then(() => {
var ParentObject = Parse.Object.extend("ParentObject"); const ParentObject = Parse.Object.extend("ParentObject");
var parent = new ParentObject(); const parent = new ParentObject();
parent.set("x", 4); parent.set("x", 4);
var relation = parent.relation("toChilds"); const relation = parent.relation("toChilds");
relation.add(childObjects[0]); relation.add(childObjects[0]);
relation.add(childObjects[1]); relation.add(childObjects[1]);
relation.add(childObjects[2]); relation.add(childObjects[2]);
var parent2 = new ParentObject(); const parent2 = new ParentObject();
parent2.set("x", 3); parent2.set("x", 3);
parent2.set("toChild", childObjects[2]); parent2.set("toChild", childObjects[2]);
var parents = []; const parents = [];
parents.push(parent); parents.push(parent);
parents.push(parent2); parents.push(parent2);
parents.push(new ParentObject()); parents.push(new ParentObject());
return Parse.Object.saveAll(parents).then(() => { return Parse.Object.saveAll(parents).then(() => {
var query = new Parse.Query(ParentObject); const query = new Parse.Query(ParentObject);
query.equalTo("objectId", parent.id); query.equalTo("objectId", parent.id);
query.equalTo("toChilds", childObjects[2]); query.equalTo("toChilds", childObjects[2]);
@@ -365,32 +365,32 @@ describe('Parse.Relation testing', () => {
}); });
it("query on pointer and relation fields with equal bis", (done) => { it("query on pointer and relation fields with equal bis", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i})); childObjects.push(new ChildObject({x: i}));
} }
Parse.Object.saveAll(childObjects).then(() => { Parse.Object.saveAll(childObjects).then(() => {
var ParentObject = Parse.Object.extend("ParentObject"); const ParentObject = Parse.Object.extend("ParentObject");
var parent = new ParentObject(); const parent = new ParentObject();
parent.set("x", 4); parent.set("x", 4);
var relation = parent.relation("toChilds"); const relation = parent.relation("toChilds");
relation.add(childObjects[0]); relation.add(childObjects[0]);
relation.add(childObjects[1]); relation.add(childObjects[1]);
relation.add(childObjects[2]); relation.add(childObjects[2]);
var parent2 = new ParentObject(); const parent2 = new ParentObject();
parent2.set("x", 3); parent2.set("x", 3);
parent2.relation("toChilds").add(childObjects[2]); parent2.relation("toChilds").add(childObjects[2]);
var parents = []; const parents = [];
parents.push(parent); parents.push(parent);
parents.push(parent2); parents.push(parent2);
parents.push(new ParentObject()); parents.push(new ParentObject());
return Parse.Object.saveAll(parents).then(() => { return Parse.Object.saveAll(parents).then(() => {
var query = new Parse.Query(ParentObject); const query = new Parse.Query(ParentObject);
query.equalTo("objectId", parent2.id); query.equalTo("objectId", parent2.id);
// childObjects[2] is in 2 relations // childObjects[2] is in 2 relations
// before the fix, that woul yield 2 results // before the fix, that woul yield 2 results
@@ -405,38 +405,38 @@ describe('Parse.Relation testing', () => {
}); });
it_exclude_dbs(['postgres'])("or queries on pointer and relation fields", (done) => { it_exclude_dbs(['postgres'])("or queries on pointer and relation fields", (done) => {
var ChildObject = Parse.Object.extend("ChildObject"); const ChildObject = Parse.Object.extend("ChildObject");
var childObjects = []; const childObjects = [];
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i})); childObjects.push(new ChildObject({x: i}));
} }
Parse.Object.saveAll(childObjects).then(() => { Parse.Object.saveAll(childObjects).then(() => {
var ParentObject = Parse.Object.extend("ParentObject"); const ParentObject = Parse.Object.extend("ParentObject");
var parent = new ParentObject(); const parent = new ParentObject();
parent.set("x", 4); parent.set("x", 4);
var relation = parent.relation("toChilds"); const relation = parent.relation("toChilds");
relation.add(childObjects[0]); relation.add(childObjects[0]);
relation.add(childObjects[1]); relation.add(childObjects[1]);
relation.add(childObjects[2]); relation.add(childObjects[2]);
var parent2 = new ParentObject(); const parent2 = new ParentObject();
parent2.set("x", 3); parent2.set("x", 3);
parent2.set("toChild", childObjects[2]); parent2.set("toChild", childObjects[2]);
var parents = []; const parents = [];
parents.push(parent); parents.push(parent);
parents.push(parent2); parents.push(parent2);
parents.push(new ParentObject()); parents.push(new ParentObject());
return Parse.Object.saveAll(parents).then(() => { return Parse.Object.saveAll(parents).then(() => {
var query1 = new Parse.Query(ParentObject); const query1 = new Parse.Query(ParentObject);
query1.containedIn("toChilds", [childObjects[2]]); query1.containedIn("toChilds", [childObjects[2]]);
var query2 = new Parse.Query(ParentObject); const query2 = new Parse.Query(ParentObject);
query2.equalTo("toChild", childObjects[2]); query2.equalTo("toChild", childObjects[2]);
var query = Parse.Query.or(query1, query2); const query = Parse.Query.or(query1, query2);
return query.find().then((list) => { return query.find().then((list) => {
var objectIds = list.map(function(item){ const objectIds = list.map(function(item){
return item.id; return item.id;
}); });
expect(objectIds.indexOf(parent.id)).not.toBe(-1); expect(objectIds.indexOf(parent.id)).not.toBe(-1);
@@ -451,21 +451,21 @@ describe('Parse.Relation testing', () => {
it("Get query on relation using un-fetched parent object", (done) => { it("Get query on relation using un-fetched parent object", (done) => {
// Setup data model // Setup data model
var Wheel = Parse.Object.extend('Wheel'); const Wheel = Parse.Object.extend('Wheel');
var Car = Parse.Object.extend('Car'); const Car = Parse.Object.extend('Car');
var origWheel = new Wheel(); const origWheel = new Wheel();
origWheel.save().then(function() { origWheel.save().then(function() {
var car = new Car(); const car = new Car();
var relation = car.relation('wheels'); const relation = car.relation('wheels');
relation.add(origWheel); relation.add(origWheel);
return car.save(); return car.save();
}).then(function(car) { }).then(function(car) {
// Test starts here. // Test starts here.
// Create an un-fetched shell car object // Create an un-fetched shell car object
var unfetchedCar = new Car(); const unfetchedCar = new Car();
unfetchedCar.id = car.id; unfetchedCar.id = car.id;
var relation = unfetchedCar.relation('wheels'); const relation = unfetchedCar.relation('wheels');
var query = relation.query(); const query = relation.query();
// Parent object is un-fetched, so this will call /1/classes/Car instead // Parent object is un-fetched, so this will call /1/classes/Car instead
// of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }. // of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }.
@@ -484,28 +484,28 @@ describe('Parse.Relation testing', () => {
it("Find query on relation using un-fetched parent object", (done) => { it("Find query on relation using un-fetched parent object", (done) => {
// Setup data model // Setup data model
var Wheel = Parse.Object.extend('Wheel'); const Wheel = Parse.Object.extend('Wheel');
var Car = Parse.Object.extend('Car'); const Car = Parse.Object.extend('Car');
var origWheel = new Wheel(); const origWheel = new Wheel();
origWheel.save().then(function() { origWheel.save().then(function() {
var car = new Car(); const car = new Car();
var relation = car.relation('wheels'); const relation = car.relation('wheels');
relation.add(origWheel); relation.add(origWheel);
return car.save(); return car.save();
}).then(function(car) { }).then(function(car) {
// Test starts here. // Test starts here.
// Create an un-fetched shell car object // Create an un-fetched shell car object
var unfetchedCar = new Car(); const unfetchedCar = new Car();
unfetchedCar.id = car.id; unfetchedCar.id = car.id;
var relation = unfetchedCar.relation('wheels'); const relation = unfetchedCar.relation('wheels');
var query = relation.query(); const query = relation.query();
// Parent object is un-fetched, so this will call /1/classes/Car instead // Parent object is un-fetched, so this will call /1/classes/Car instead
// of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }. // of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }.
return query.find(origWheel.id); return query.find(origWheel.id);
}).then(function(results) { }).then(function(results) {
// Make sure this is Wheel and not Car. // Make sure this is Wheel and not Car.
var wheel = results[0]; const wheel = results[0];
strictEqual(wheel.className, 'Wheel'); strictEqual(wheel.className, 'Wheel');
strictEqual(wheel.id, origWheel.id); strictEqual(wheel.id, origWheel.id);
}).then(function() { }).then(function() {
@@ -518,16 +518,16 @@ describe('Parse.Relation testing', () => {
it('Find objects with a related object using equalTo', (done) => { it('Find objects with a related object using equalTo', (done) => {
// Setup the objects // Setup the objects
var Card = Parse.Object.extend('Card'); const Card = Parse.Object.extend('Card');
var House = Parse.Object.extend('House'); const House = Parse.Object.extend('House');
var card = new Card(); const card = new Card();
card.save().then(() => { card.save().then(() => {
var house = new House(); const house = new House();
var relation = house.relation('cards'); const relation = house.relation('cards');
relation.add(card); relation.add(card);
return house.save(); return house.save();
}).then(() => { }).then(() => {
var query = new Parse.Query('House'); const query = new Parse.Query('House');
query.equalTo('cards', card); query.equalTo('cards', card);
return query.find(); return query.find();
}).then((results) => { }).then((results) => {
@@ -609,10 +609,10 @@ describe('Parse.Relation testing', () => {
}); });
it("select query", function(done) { it("select query", function(done) {
var RestaurantObject = Parse.Object.extend("Restaurant"); const RestaurantObject = Parse.Object.extend("Restaurant");
var PersonObject = Parse.Object.extend("Person"); const PersonObject = Parse.Object.extend("Person");
var OwnerObject = Parse.Object.extend('Owner'); const OwnerObject = Parse.Object.extend('Owner');
var restaurants = [ const restaurants = [
new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 5, location: "Djibouti" }),
new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }),
]; ];
@@ -630,9 +630,9 @@ describe('Parse.Relation testing', () => {
}).then(() => { }).then(() => {
const unfetchedOwner = new OwnerObject(); const unfetchedOwner = new OwnerObject();
unfetchedOwner.id = owner.id; unfetchedOwner.id = owner.id;
var query = unfetchedOwner.relation('restaurants').query(); const query = unfetchedOwner.relation('restaurants').query();
query.greaterThan("ratings", 4); query.greaterThan("ratings", 4);
var mainQuery = new Parse.Query(PersonObject); const mainQuery = new Parse.Query(PersonObject);
mainQuery.matchesKeyInQuery("hometown", "location", query); mainQuery.matchesKeyInQuery("hometown", "location", query);
mainQuery.find(expectSuccess({ mainQuery.find(expectSuccess({
success: function(results) { success: function(results) {
@@ -650,10 +650,10 @@ describe('Parse.Relation testing', () => {
}); });
it("dontSelect query", function(done) { it("dontSelect query", function(done) {
var RestaurantObject = Parse.Object.extend("Restaurant"); const RestaurantObject = Parse.Object.extend("Restaurant");
var PersonObject = Parse.Object.extend("Person"); const PersonObject = Parse.Object.extend("Person");
var OwnerObject = Parse.Object.extend('Owner'); const OwnerObject = Parse.Object.extend('Owner');
var restaurants = [ const restaurants = [
new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 5, location: "Djibouti" }),
new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }),
]; ];
@@ -671,9 +671,9 @@ describe('Parse.Relation testing', () => {
}).then(() => { }).then(() => {
const unfetchedOwner = new OwnerObject(); const unfetchedOwner = new OwnerObject();
unfetchedOwner.id = owner.id; unfetchedOwner.id = owner.id;
var query = unfetchedOwner.relation('restaurants').query(); const query = unfetchedOwner.relation('restaurants').query();
query.greaterThan("ratings", 4); query.greaterThan("ratings", 4);
var mainQuery = new Parse.Query(PersonObject); const mainQuery = new Parse.Query(PersonObject);
mainQuery.doesNotMatchKeyInQuery("hometown", "location", query); mainQuery.doesNotMatchKeyInQuery("hometown", "location", query);
mainQuery.ascending('name'); mainQuery.ascending('name');
mainQuery.find(expectSuccess({ mainQuery.find(expectSuccess({

View File

@@ -2,14 +2,14 @@
// Roles are not accessible without the master key, so they are not intended // Roles are not accessible without the master key, so they are not intended
// for use by clients. We can manually test them using the master key. // for use by clients. We can manually test them using the master key.
var RestQuery = require("../src/RestQuery"); const RestQuery = require("../src/RestQuery");
var Auth = require("../src/Auth").Auth; const Auth = require("../src/Auth").Auth;
var Config = require("../src/Config"); const Config = require("../src/Config");
describe('Parse Role testing', () => { describe('Parse Role testing', () => {
it('Do a bunch of basic role testing', done => { it('Do a bunch of basic role testing', done => {
var user; let user;
var role; let role;
createTestUser().then((x) => { createTestUser().then((x) => {
user = x; user = x;
@@ -19,23 +19,23 @@ describe('Parse Role testing', () => {
role = new Parse.Object('_Role'); role = new Parse.Object('_Role');
role.set('name', 'Foos'); role.set('name', 'Foos');
role.setACL(acl); role.setACL(acl);
var users = role.relation('users'); const users = role.relation('users');
users.add(user); users.add(user);
return role.save({}, { useMasterKey: true }); return role.save({}, { useMasterKey: true });
}).then(() => { }).then(() => {
var query = new Parse.Query('_Role'); const query = new Parse.Query('_Role');
return query.find({ useMasterKey: true }); return query.find({ useMasterKey: true });
}).then((x) => { }).then((x) => {
expect(x.length).toEqual(1); expect(x.length).toEqual(1);
var relation = x[0].relation('users').query(); const relation = x[0].relation('users').query();
return relation.first({ useMasterKey: true }); return relation.first({ useMasterKey: true });
}).then((x) => { }).then((x) => {
expect(x.id).toEqual(user.id); expect(x.id).toEqual(user.id);
// Here we've got a valid role and a user assigned. // Here we've got a valid role and a user assigned.
// Lets create an object only the role can read/write and test // Lets create an object only the role can read/write and test
// the different scenarios. // the different scenarios.
var obj = new Parse.Object('TestObject'); const obj = new Parse.Object('TestObject');
var acl = new Parse.ACL(); const acl = new Parse.ACL();
acl.setPublicReadAccess(false); acl.setPublicReadAccess(false);
acl.setPublicWriteAccess(false); acl.setPublicWriteAccess(false);
acl.setRoleReadAccess('Foos', true); acl.setRoleReadAccess('Foos', true);
@@ -43,11 +43,11 @@ describe('Parse Role testing', () => {
obj.setACL(acl); obj.setACL(acl);
return obj.save(); return obj.save();
}).then(() => { }).then(() => {
var query = new Parse.Query('TestObject'); const query = new Parse.Query('TestObject');
return query.find({ sessionToken: user.getSessionToken() }); return query.find({ sessionToken: user.getSessionToken() });
}).then((x) => { }).then((x) => {
expect(x.length).toEqual(1); expect(x.length).toEqual(1);
var objAgain = x[0]; const objAgain = x[0];
objAgain.set('foo', 'bar'); objAgain.set('foo', 'bar');
// This should succeed: // This should succeed:
return objAgain.save({}, {sessionToken: user.getSessionToken()}); return objAgain.save({}, {sessionToken: user.getSessionToken()});
@@ -64,10 +64,10 @@ describe('Parse Role testing', () => {
}); });
var createRole = function(name, sibling, user) { const createRole = function(name, sibling, user) {
var role = new Parse.Role(name, new Parse.ACL()); const role = new Parse.Role(name, new Parse.ACL());
if (user) { if (user) {
var users = role.relation('users'); const users = role.relation('users');
users.add(user); users.add(user);
} }
if (sibling) { if (sibling) {
@@ -77,13 +77,13 @@ describe('Parse Role testing', () => {
}; };
it("should not recursively load the same role multiple times", (done) => { it("should not recursively load the same role multiple times", (done) => {
var rootRole = "RootRole"; const rootRole = "RootRole";
var roleNames = ["FooRole", "BarRole", "BazRole"]; const roleNames = ["FooRole", "BarRole", "BazRole"];
var allRoles = [rootRole].concat(roleNames); const allRoles = [rootRole].concat(roleNames);
var roleObjs = {}; const roleObjs = {};
var createAllRoles = function(user) { const createAllRoles = function(user) {
var promises = allRoles.map(function(roleName) { const promises = allRoles.map(function(roleName) {
return createRole(roleName, null, user) return createRole(roleName, null, user)
.then(function(roleObj) { .then(function(roleObj) {
roleObjs[roleName] = roleObj; roleObjs[roleName] = roleObj;
@@ -93,16 +93,16 @@ describe('Parse Role testing', () => {
return Promise.all(promises); return Promise.all(promises);
}; };
var restExecute = spyOn(RestQuery.prototype, "execute").and.callThrough(); const restExecute = spyOn(RestQuery.prototype, "execute").and.callThrough();
var user, let user,
auth, auth,
getAllRolesSpy; getAllRolesSpy;
createTestUser().then((newUser) => { createTestUser().then((newUser) => {
user = newUser; user = newUser;
return createAllRoles(user); return createAllRoles(user);
}).then ((roles) => { }).then ((roles) => {
var rootRoleObj = roleObjs[rootRole]; const rootRoleObj = roleObjs[rootRole];
roles.forEach(function(role, i) { roles.forEach(function(role, i) {
// Add all roles to the RootRole // Add all roles to the RootRole
if (role.id !== rootRoleObj.id) { if (role.id !== rootRoleObj.id) {
@@ -143,8 +143,8 @@ describe('Parse Role testing', () => {
}); });
it("should recursively load roles", (done) => { it("should recursively load roles", (done) => {
var rolesNames = ["FooRole", "BarRole", "BazRole"]; const rolesNames = ["FooRole", "BarRole", "BazRole"];
var roleIds = {}; const roleIds = {};
createTestUser().then((user) => { createTestUser().then((user) => {
// Put the user on the 1st role // Put the user on the 1st role
return createRole(rolesNames[0], null, user).then((aRole) => { return createRole(rolesNames[0], null, user).then((aRole) => {
@@ -159,7 +159,7 @@ describe('Parse Role testing', () => {
return createRole(rolesNames[2], anotherRole, null); return createRole(rolesNames[2], anotherRole, null);
}).then((lastRole) => { }).then((lastRole) => {
roleIds[lastRole.get("name")] = lastRole.id; roleIds[lastRole.get("name")] = lastRole.id;
var auth = new Auth({ config: Config.get("test"), isMaster: true, user: user }); const auth = new Auth({ config: Config.get("test"), isMaster: true, user: user });
return auth._loadRoles(); return auth._loadRoles();
}) })
}).then((roles) => { }).then((roles) => {
@@ -175,7 +175,7 @@ describe('Parse Role testing', () => {
}); });
it("_Role object should not save without name.", (done) => { it("_Role object should not save without name.", (done) => {
var role = new Parse.Role(); const role = new Parse.Role();
role.save(null,{useMasterKey:true}) role.save(null,{useMasterKey:true})
.then(() => { .then(() => {
fail("_Role object should not save without name."); fail("_Role object should not save without name.");
@@ -222,7 +222,7 @@ describe('Parse Role testing', () => {
superContentManager.getRoles().add(superModerator); superContentManager.getRoles().add(superModerator);
return Parse.Object.saveAll([admin, moderator, contentManager, superModerator, superContentManager], {useMasterKey: true}); return Parse.Object.saveAll([admin, moderator, contentManager, superModerator, superContentManager], {useMasterKey: true});
}).then(() => { }).then(() => {
var auth = new Auth({ config: Config.get("test"), isMaster: true }); const auth = new Auth({ config: Config.get("test"), isMaster: true });
// For each role, fetch their sibling, what they inherit // For each role, fetch their sibling, what they inherit
// return with result and roleId for later comparison // return with result and roleId for later comparison
const promises = [admin, moderator, contentManager, superModerator].map((role) => { const promises = [admin, moderator, contentManager, superModerator].map((role) => {
@@ -264,12 +264,12 @@ describe('Parse Role testing', () => {
}); });
it('can create role and query empty users', (done)=> { it('can create role and query empty users', (done)=> {
var roleACL = new Parse.ACL(); const roleACL = new Parse.ACL();
roleACL.setPublicReadAccess(true); roleACL.setPublicReadAccess(true);
var role = new Parse.Role('subscribers', roleACL); const role = new Parse.Role('subscribers', roleACL);
role.save({}, {useMasterKey : true}) role.save({}, {useMasterKey : true})
.then(()=>{ .then(()=>{
var query = role.relation('users').query(); const query = role.relation('users').query();
query.find({useMasterKey : true}) query.find({useMasterKey : true})
.then(()=>{ .then(()=>{
done(); done();
@@ -284,13 +284,13 @@ describe('Parse Role testing', () => {
// Based on various scenarios described in issues #827 and #683, // Based on various scenarios described in issues #827 and #683,
it('should properly handle role permissions on objects', (done) => { it('should properly handle role permissions on objects', (done) => {
var user, user2, user3; let user, user2, user3;
var role, role2, role3; let role, role2, role3;
var obj, obj2; let obj, obj2;
var prACL = new Parse.ACL(); const prACL = new Parse.ACL();
prACL.setPublicReadAccess(true); prACL.setPublicReadAccess(true);
var adminACL, superACL, customerACL; let adminACL, superACL, customerACL;
createTestUser().then((x) => { createTestUser().then((x) => {
user = x; user = x;
@@ -328,7 +328,7 @@ describe('Parse Role testing', () => {
customerACL.setRoleReadAccess("Customer", true); customerACL.setRoleReadAccess("Customer", true);
customerACL.setRoleWriteAccess("Customer", true); customerACL.setRoleWriteAccess("Customer", true);
var query = new Parse.Query('_Role'); const query = new Parse.Query('_Role');
return query.find({ useMasterKey: true }); return query.find({ useMasterKey: true });
}).then((x) => { }).then((x) => {
expect(x.length).toEqual(3); expect(x.length).toEqual(3);
@@ -366,11 +366,11 @@ describe('Parse Role testing', () => {
}); });
it('should add multiple users to a role and remove users', (done) => { it('should add multiple users to a role and remove users', (done) => {
var user, user2, user3; let user, user2, user3;
var role; let role;
var obj; let obj;
var prACL = new Parse.ACL(); const prACL = new Parse.ACL();
prACL.setPublicReadAccess(true); prACL.setPublicReadAccess(true);
prACL.setPublicWriteAccess(true); prACL.setPublicWriteAccess(true);
@@ -383,19 +383,19 @@ describe('Parse Role testing', () => {
return user3.save({ username: 'user3', password: 'omgbbq' }); return user3.save({ username: 'user3', password: 'omgbbq' });
}).then(() => { }).then(() => {
role = new Parse.Role('sharedRole', prACL); role = new Parse.Role('sharedRole', prACL);
var users = role.relation('users'); const users = role.relation('users');
users.add(user); users.add(user);
users.add(user2); users.add(user2);
users.add(user3); users.add(user3);
return role.save({}, { useMasterKey: true }); return role.save({}, { useMasterKey: true });
}).then(() => { }).then(() => {
// query for saved role and get 3 users // query for saved role and get 3 users
var query = new Parse.Query('_Role'); const query = new Parse.Query('_Role');
query.equalTo('name', 'sharedRole'); query.equalTo('name', 'sharedRole');
return query.find({ useMasterKey: true }); return query.find({ useMasterKey: true });
}).then((role) => { }).then((role) => {
expect(role.length).toEqual(1); expect(role.length).toEqual(1);
var users = role[0].relation('users').query(); const users = role[0].relation('users').query();
return users.find({ useMasterKey: true }); return users.find({ useMasterKey: true });
}).then((users) => { }).then((users) => {
expect(users.length).toEqual(3); expect(users.length).toEqual(3);
@@ -409,17 +409,17 @@ describe('Parse Role testing', () => {
return obj.save(null, { sessionToken: user.getSessionToken() }); return obj.save(null, { sessionToken: user.getSessionToken() });
}).then(() => { }).then(() => {
// query for saved role and get 3 users // query for saved role and get 3 users
var query = new Parse.Query('_Role'); const query = new Parse.Query('_Role');
query.equalTo('name', 'sharedRole'); query.equalTo('name', 'sharedRole');
return query.find({ useMasterKey: true }); return query.find({ useMasterKey: true });
}).then((role) => { }).then((role) => {
expect(role.length).toEqual(1); expect(role.length).toEqual(1);
var users = role[0].relation('users'); const users = role[0].relation('users');
users.remove(user); users.remove(user);
users.remove(user3); users.remove(user3);
return role[0].save({}, { useMasterKey: true }); return role[0].save({}, { useMasterKey: true });
}).then((role) =>{ }).then((role) =>{
var users = role.relation('users').query(); const users = role.relation('users').query();
return users.find({ useMasterKey: true }); return users.find({ useMasterKey: true });
}).then((users) => { }).then((users) => {
expect(users.length).toEqual(1); expect(users.length).toEqual(1);
@@ -449,20 +449,20 @@ describe('Parse Role testing', () => {
}); });
it('should match when matching in users relation', (done) => { it('should match when matching in users relation', (done) => {
var user = new Parse.User(); const user = new Parse.User();
user user
.save({ username: 'admin', password: 'admin' }) .save({ username: 'admin', password: 'admin' })
.then((user) => { .then((user) => {
var aCL = new Parse.ACL(); const aCL = new Parse.ACL();
aCL.setPublicReadAccess(true); aCL.setPublicReadAccess(true);
aCL.setPublicWriteAccess(true); aCL.setPublicWriteAccess(true);
var role = new Parse.Role('admin', aCL); const role = new Parse.Role('admin', aCL);
var users = role.relation('users'); const users = role.relation('users');
users.add(user); users.add(user);
role role
.save({}, { useMasterKey: true }) .save({}, { useMasterKey: true })
.then(() => { .then(() => {
var query = new Parse.Query(Parse.Role); const query = new Parse.Query(Parse.Role);
query.equalTo('name', 'admin'); query.equalTo('name', 'admin');
query.equalTo('users', user); query.equalTo('users', user);
query.find().then(function (roles) { query.find().then(function (roles) {
@@ -474,24 +474,24 @@ describe('Parse Role testing', () => {
}); });
it('should not match any entry when not matching in users relation', (done) => { it('should not match any entry when not matching in users relation', (done) => {
var user = new Parse.User(); const user = new Parse.User();
user user
.save({ username: 'admin', password: 'admin' }) .save({ username: 'admin', password: 'admin' })
.then((user) => { .then((user) => {
var aCL = new Parse.ACL(); const aCL = new Parse.ACL();
aCL.setPublicReadAccess(true); aCL.setPublicReadAccess(true);
aCL.setPublicWriteAccess(true); aCL.setPublicWriteAccess(true);
var role = new Parse.Role('admin', aCL); const role = new Parse.Role('admin', aCL);
var users = role.relation('users'); const users = role.relation('users');
users.add(user); users.add(user);
role role
.save({}, { useMasterKey: true }) .save({}, { useMasterKey: true })
.then(() => { .then(() => {
var otherUser = new Parse.User(); const otherUser = new Parse.User();
otherUser otherUser
.save({ username: 'otherUser', password: 'otherUser' }) .save({ username: 'otherUser', password: 'otherUser' })
.then((otherUser) => { .then((otherUser) => {
var query = new Parse.Query(Parse.Role); const query = new Parse.Query(Parse.Role);
query.equalTo('name', 'admin'); query.equalTo('name', 'admin');
query.equalTo('users', otherUser); query.equalTo('users', otherUser);
query.find().then(function(roles) { query.find().then(function(roles) {
@@ -504,20 +504,20 @@ describe('Parse Role testing', () => {
}); });
it('should not match any entry when searching for null in users relation', (done) => { it('should not match any entry when searching for null in users relation', (done) => {
var user = new Parse.User(); const user = new Parse.User();
user user
.save({ username: 'admin', password: 'admin' }) .save({ username: 'admin', password: 'admin' })
.then((user) => { .then((user) => {
var aCL = new Parse.ACL(); const aCL = new Parse.ACL();
aCL.setPublicReadAccess(true); aCL.setPublicReadAccess(true);
aCL.setPublicWriteAccess(true); aCL.setPublicWriteAccess(true);
var role = new Parse.Role('admin', aCL); const role = new Parse.Role('admin', aCL);
var users = role.relation('users'); const users = role.relation('users');
users.add(user); users.add(user);
role role
.save({}, { useMasterKey: true }) .save({}, { useMasterKey: true })
.then(() => { .then(() => {
var query = new Parse.Query(Parse.Role); const query = new Parse.Query(Parse.Role);
query.equalTo('name', 'admin'); query.equalTo('name', 'admin');
query.equalTo('users', null); query.equalTo('users', null);
query.find().then(function (roles) { query.find().then(function (roles) {

File diff suppressed because it is too large Load Diff

View File

@@ -1,41 +1,41 @@
var ParseWebSocket = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocket; const ParseWebSocket = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocket;
describe('ParseWebSocket', function() { describe('ParseWebSocket', function() {
it('can be initialized', function() { it('can be initialized', function() {
var ws = {}; const ws = {};
var parseWebSocket = new ParseWebSocket(ws); const parseWebSocket = new ParseWebSocket(ws);
expect(parseWebSocket.ws).toBe(ws); expect(parseWebSocket.ws).toBe(ws);
}); });
it('can handle events defined in typeMap', function() { it('can handle events defined in typeMap', function() {
var ws = { const ws = {
on: jasmine.createSpy('on') on: jasmine.createSpy('on')
}; };
var callback = {}; const callback = {};
var parseWebSocket = new ParseWebSocket(ws); const parseWebSocket = new ParseWebSocket(ws);
parseWebSocket.on('disconnect', callback); parseWebSocket.on('disconnect', callback);
expect(parseWebSocket.ws.on).toHaveBeenCalledWith('close', callback); expect(parseWebSocket.ws.on).toHaveBeenCalledWith('close', callback);
}); });
it('can handle events which are not defined in typeMap', function() { it('can handle events which are not defined in typeMap', function() {
var ws = { const ws = {
on: jasmine.createSpy('on') on: jasmine.createSpy('on')
}; };
var callback = {}; const callback = {};
var parseWebSocket = new ParseWebSocket(ws); const parseWebSocket = new ParseWebSocket(ws);
parseWebSocket.on('open', callback); parseWebSocket.on('open', callback);
expect(parseWebSocket.ws.on).toHaveBeenCalledWith('open', callback); expect(parseWebSocket.ws.on).toHaveBeenCalledWith('open', callback);
}); });
it('can send a message', function() { it('can send a message', function() {
var ws = { const ws = {
send: jasmine.createSpy('send') send: jasmine.createSpy('send')
}; };
var parseWebSocket = new ParseWebSocket(ws); const parseWebSocket = new ParseWebSocket(ws);
parseWebSocket.send('message') parseWebSocket.send('message')
expect(parseWebSocket.ws.send).toHaveBeenCalledWith('message'); expect(parseWebSocket.ws.send).toHaveBeenCalledWith('message');

View File

@@ -1,11 +1,11 @@
var ParseWebSocketServer = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocketServer; const ParseWebSocketServer = require('../src/LiveQuery/ParseWebSocketServer').ParseWebSocketServer;
describe('ParseWebSocketServer', function() { describe('ParseWebSocketServer', function() {
beforeEach(function(done) { beforeEach(function(done) {
// Mock ws server // Mock ws server
var EventEmitter = require('events'); const EventEmitter = require('events');
var mockServer = function() { const mockServer = function() {
return new EventEmitter(); return new EventEmitter();
}; };
jasmine.mockLibrary('ws', 'Server', mockServer); jasmine.mockLibrary('ws', 'Server', mockServer);
@@ -13,11 +13,11 @@ describe('ParseWebSocketServer', function() {
}); });
it('can handle connect event when ws is open', function(done) { it('can handle connect event when ws is open', function(done) {
var onConnectCallback = jasmine.createSpy('onConnectCallback'); const onConnectCallback = jasmine.createSpy('onConnectCallback');
var http = require('http'); const http = require('http');
var server = http.createServer(); const server = http.createServer();
var parseWebSocketServer = new ParseWebSocketServer(server, onConnectCallback, 5).server; const parseWebSocketServer = new ParseWebSocketServer(server, onConnectCallback, 5).server;
var ws = { const ws = {
readyState: 0, readyState: 0,
OPEN: 0, OPEN: 0,
ping: jasmine.createSpy('ping') ping: jasmine.createSpy('ping')

View File

@@ -1,5 +1,5 @@
'use strict'; 'use strict';
var Config = require('../src/Config'); const Config = require('../src/Config');
describe('Pointer Permissions', () => { describe('Pointer Permissions', () => {

View File

@@ -43,7 +43,7 @@ dbOptionsTest[`${baseURI}?ssl=&binary=aa`] = {
describe('PostgresConfigParser.getDatabaseOptionsFromURI', () => { describe('PostgresConfigParser.getDatabaseOptionsFromURI', () => {
it('creates a db options map from a query string', () => { it('creates a db options map from a query string', () => {
for (const key in dbOptionsTest) { for (const key in dbOptionsTest) {
const result = parser.getDatabaseOptionsFromURI(key); const result = parser.getDatabaseOptionsFromURI(key);
const testObj = dbOptionsTest[key]; const testObj = dbOptionsTest[key];

View File

@@ -38,7 +38,7 @@ function createParseServer(options) {
promise promise
.then(() => { .then(() => {
expect(Parse.applicationId).toEqual("test"); expect(Parse.applicationId).toEqual("test");
var app = express(); const app = express();
app.use('/parse', parseServer.app); app.use('/parse', parseServer.app);
const server = app.listen(12666); const server = app.listen(12666);
@@ -66,7 +66,7 @@ describe_only_db('postgres')('Postgres database init options', () => {
createParseServer({ databaseAdapter: adapter }).then((newServer) => { createParseServer({ databaseAdapter: adapter }).then((newServer) => {
server = newServer; server = newServer;
var score = new GameScore({ "score": 1337, "playerName": "Sean Plott", "cheatMode": false }); const score = new GameScore({ "score": 1337, "playerName": "Sean Plott", "cheatMode": false });
return score.save(); return score.save();
}).then(done, done.fail); }).then(done, done.fail);
}); });
@@ -77,6 +77,6 @@ describe_only_db('postgres')('Postgres database init options', () => {
databaseOptions: databaseOptions2 databaseOptions: databaseOptions2
}) })
createParseServer({ databaseAdapter: adapter }).then(done.fail, done); createParseServer({ databaseAdapter: adapter }).then(done.fail, () => done());
}); });
}); });

View File

@@ -5,27 +5,17 @@ const getColumns = (client, className) => {
return client.map('SELECT column_name FROM information_schema.columns WHERE table_name = $<className>', { className }, a => a.column_name); return client.map('SELECT column_name FROM information_schema.columns WHERE table_name = $<className>', { className }, a => a.column_name);
}; };
const dropTable = (client, className) => {
return client.none('DROP TABLE IF EXISTS $<className:name>', { className });
}
describe_only_db('postgres')('PostgresStorageAdapter', () => { describe_only_db('postgres')('PostgresStorageAdapter', () => {
beforeEach(done => { const adapter = new PostgresStorageAdapter({ uri: databaseURI })
const adapter = new PostgresStorageAdapter({ uri: databaseURI }) beforeEach(() => {
.deleteAllClasses() return adapter.deleteAllClasses();
.then(() => {
adapter.handleShutdown();
}, fail)
.catch(done);
});
it('handleShutdown, close connection', (done) => {
const adapter = new PostgresStorageAdapter({ uri: databaseURI });
expect(adapter._client.$pool.ending).toEqual(false);
adapter.handleShutdown();
expect(adapter._client.$pool.ending).toEqual(true);
done();
}); });
it('schemaUpgrade, upgrade the database schema when schema changes', done => { it('schemaUpgrade, upgrade the database schema when schema changes', done => {
const adapter = new PostgresStorageAdapter({ uri: databaseURI });
const client = adapter._client; const client = adapter._client;
const className = '_PushStatus'; const className = '_PushStatus';
const schema = { const schema = {
@@ -59,7 +49,6 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => {
}); });
it('schemaUpgrade, maintain correct schema', done => { it('schemaUpgrade, maintain correct schema', done => {
const adapter = new PostgresStorageAdapter({ uri: databaseURI });
const client = adapter._client; const client = adapter._client;
const className = 'Table'; const className = 'Table';
const schema = { const schema = {
@@ -91,24 +80,21 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => {
}); });
it('Create a table without columns and upgrade with columns', done => { it('Create a table without columns and upgrade with columns', done => {
const adapter = new PostgresStorageAdapter({ uri: databaseURI });
const client = adapter._client; const client = adapter._client;
const className = 'EmptyTable'; const className = 'EmptyTable';
let schema = {}; dropTable(client, className).then(() => adapter.createTable(className, {}))
adapter.createTable(className, schema)
.then(() => getColumns(client, className)) .then(() => getColumns(client, className))
.then(columns => { .then(columns => {
expect(columns.length).toBe(0); expect(columns.length).toBe(0);
schema = { const newSchema = {
fields: { fields: {
"columnA": { type: 'String' }, "columnA": { type: 'String' },
"columnB": { type: 'String' } "columnB": { type: 'String' }
}, },
}; };
return adapter.schemaUpgrade(className, schema); return adapter.schemaUpgrade(className, newSchema);
}) })
.then(() => getColumns(client, className)) .then(() => getColumns(client, className))
.then(columns => { .then(columns => {
@@ -117,6 +103,15 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => {
expect(columns).toContain('columnB'); expect(columns).toContain('columnB');
done(); done();
}) })
.catch(error => done.fail(error)); .catch(done);
}) });
});
describe_only_db('postgres')('PostgresStorageAdapter shutdown', () => {
it('handleShutdown, close connection', () => {
const adapter = new PostgresStorageAdapter({ uri: databaseURI });
expect(adapter._client.$pool.ending).toEqual(false);
adapter.handleShutdown();
expect(adapter._client.$pool.ending).toEqual(true);
});
}); });

View File

@@ -1,8 +1,8 @@
var PromiseRouter = require("../src/PromiseRouter").default; const PromiseRouter = require("../src/PromiseRouter").default;
describe("PromiseRouter", () => { describe("PromiseRouter", () => {
it("should properly handle rejects", (done) => { it("should properly handle rejects", (done) => {
var router = new PromiseRouter(); const router = new PromiseRouter();
router.route("GET", "/dummy", ()=> { router.route("GET", "/dummy", ()=> {
return Promise.reject({ return Promise.reject({
error: "an error", error: "an error",

View File

@@ -1,5 +1,5 @@
var request = require('request'); const request = require('request');
describe("public API", () => { describe("public API", () => {
it("should get invalid_link.html", (done) => { it("should get invalid_link.html", (done) => {

View File

@@ -1,11 +1,11 @@
var request = require("request"); const request = require("request");
function createProduct() { function createProduct() {
const file = new Parse.File("name", { const file = new Parse.File("name", {
base64: new Buffer("download_file", "utf-8").toString("base64") base64: new Buffer("download_file", "utf-8").toString("base64")
}, "text"); }, "text");
return file.save().then(function(){ return file.save().then(function(){
var product = new Parse.Object("_Product"); const product = new Parse.Object("_Product");
product.set({ product.set({
download: file, download: file,
icon: file, icon: file,
@@ -160,7 +160,7 @@ describe("test validate_receipt endpoint", () => {
}); });
it("should not create a _Product", (done) => { it("should not create a _Product", (done) => {
var product = new Parse.Object("_Product"); const product = new Parse.Object("_Product");
product.save().then(function(){ product.save().then(function(){
fail("Should not be able to save"); fail("Should not be able to save");
done(); done();
@@ -171,7 +171,7 @@ describe("test validate_receipt endpoint", () => {
}); });
it("should be able to update a _Product", (done) => { it("should be able to update a _Product", (done) => {
var query = new Parse.Query("_Product"); const query = new Parse.Query("_Product");
query.first().then(function(product) { query.first().then(function(product) {
if (!product) { if (!product) {
return Promise.reject(new Error('Product should be found')); return Promise.reject(new Error('Product should be found'));
@@ -189,7 +189,7 @@ describe("test validate_receipt endpoint", () => {
}); });
it("should not be able to remove a require key in a _Product", (done) => { it("should not be able to remove a require key in a _Product", (done) => {
var query = new Parse.Query("_Product"); const query = new Parse.Query("_Product");
query.first().then(function(product){ query.first().then(function(product){
if (!product) { if (!product) {
return Promise.reject(new Error('Product should be found')); return Promise.reject(new Error('Product should be found'));

View File

@@ -1,8 +1,8 @@
"use strict"; "use strict";
var PushController = require('../src/Controllers/PushController').PushController; const PushController = require('../src/Controllers/PushController').PushController;
var StatusHandler = require('../src/StatusHandler'); const StatusHandler = require('../src/StatusHandler');
var Config = require('../src/Config'); const Config = require('../src/Config');
var validatePushType = require('../src/Push/utils').validatePushType; const validatePushType = require('../src/Push/utils').validatePushType;
const successfulTransmissions = function(body, installations) { const successfulTransmissions = function(body, installations) {
@@ -31,9 +31,9 @@ const successfulIOS = function(body, installations) {
describe('PushController', () => { describe('PushController', () => {
it('can validate device type when no device type is set', (done) => { it('can validate device type when no device type is set', (done) => {
// Make query condition // Make query condition
var where = { const where = {
}; };
var validPushTypes = ['ios', 'android']; const validPushTypes = ['ios', 'android'];
expect(function(){ expect(function(){
validatePushType(where, validPushTypes); validatePushType(where, validPushTypes);
@@ -43,10 +43,10 @@ describe('PushController', () => {
it('can validate device type when single valid device type is set', (done) => { it('can validate device type when single valid device type is set', (done) => {
// Make query condition // Make query condition
var where = { const where = {
'deviceType': 'ios' 'deviceType': 'ios'
}; };
var validPushTypes = ['ios', 'android']; const validPushTypes = ['ios', 'android'];
expect(function(){ expect(function(){
validatePushType(where, validPushTypes); validatePushType(where, validPushTypes);
@@ -56,12 +56,12 @@ describe('PushController', () => {
it('can validate device type when multiple valid device types are set', (done) => { it('can validate device type when multiple valid device types are set', (done) => {
// Make query condition // Make query condition
var where = { const where = {
'deviceType': { 'deviceType': {
'$in': ['android', 'ios'] '$in': ['android', 'ios']
} }
}; };
var validPushTypes = ['ios', 'android']; const validPushTypes = ['ios', 'android'];
expect(function(){ expect(function(){
validatePushType(where, validPushTypes); validatePushType(where, validPushTypes);
@@ -71,10 +71,10 @@ describe('PushController', () => {
it('can throw on validateDeviceType when single invalid device type is set', (done) => { it('can throw on validateDeviceType when single invalid device type is set', (done) => {
// Make query condition // Make query condition
var where = { const where = {
'deviceType': 'osx' 'deviceType': 'osx'
}; };
var validPushTypes = ['ios', 'android']; const validPushTypes = ['ios', 'android'];
expect(function(){ expect(function(){
validatePushType(where, validPushTypes); validatePushType(where, validPushTypes);
@@ -84,10 +84,10 @@ describe('PushController', () => {
it('can throw on validateDeviceType when single invalid device type is set', (done) => { it('can throw on validateDeviceType when single invalid device type is set', (done) => {
// Make query condition // Make query condition
var where = { const where = {
'deviceType': 'osx' 'deviceType': 'osx'
}; };
var validPushTypes = ['ios', 'android']; const validPushTypes = ['ios', 'android'];
expect(function(){ expect(function(){
validatePushType(where, validPushTypes); validatePushType(where, validPushTypes);
@@ -97,31 +97,31 @@ describe('PushController', () => {
it('can get expiration time in string format', (done) => { it('can get expiration time in string format', (done) => {
// Make mock request // Make mock request
var timeStr = '2015-03-19T22:05:08Z'; const timeStr = '2015-03-19T22:05:08Z';
var body = { const body = {
'expiration_time': timeStr 'expiration_time': timeStr
} }
var time = PushController.getExpirationTime(body); const time = PushController.getExpirationTime(body);
expect(time).toEqual(new Date(timeStr).valueOf()); expect(time).toEqual(new Date(timeStr).valueOf());
done(); done();
}); });
it('can get expiration time in number format', (done) => { it('can get expiration time in number format', (done) => {
// Make mock request // Make mock request
var timeNumber = 1426802708; const timeNumber = 1426802708;
var body = { const body = {
'expiration_time': timeNumber 'expiration_time': timeNumber
} }
var time = PushController.getExpirationTime(body); const time = PushController.getExpirationTime(body);
expect(time).toEqual(timeNumber * 1000); expect(time).toEqual(timeNumber * 1000);
done(); done();
}); });
it('can throw on getExpirationTime in invalid format', (done) => { it('can throw on getExpirationTime in invalid format', (done) => {
// Make mock request // Make mock request
var body = { const body = {
'expiration_time': 'abcd' 'expiration_time': 'abcd'
} }
@@ -133,31 +133,31 @@ describe('PushController', () => {
it('can get push time in string format', (done) => { it('can get push time in string format', (done) => {
// Make mock request // Make mock request
var timeStr = '2015-03-19T22:05:08Z'; const timeStr = '2015-03-19T22:05:08Z';
var body = { const body = {
'push_time': timeStr 'push_time': timeStr
} }
var { date } = PushController.getPushTime(body); const { date } = PushController.getPushTime(body);
expect(date).toEqual(new Date(timeStr)); expect(date).toEqual(new Date(timeStr));
done(); done();
}); });
it('can get push time in number format', (done) => { it('can get push time in number format', (done) => {
// Make mock request // Make mock request
var timeNumber = 1426802708; const timeNumber = 1426802708;
var body = { const body = {
'push_time': timeNumber 'push_time': timeNumber
} }
var { date } = PushController.getPushTime(body); const { date } = PushController.getPushTime(body);
expect(date.valueOf()).toEqual(timeNumber * 1000); expect(date.valueOf()).toEqual(timeNumber * 1000);
done(); done();
}); });
it('can throw on getPushTime in invalid format', (done) => { it('can throw on getPushTime in invalid format', (done) => {
// Make mock request // Make mock request
var body = { const body = {
'push_time': 'abcd' 'push_time': 'abcd'
} }
@@ -168,9 +168,9 @@ describe('PushController', () => {
}); });
it('properly increment badges', (done) => { it('properly increment badges', (done) => {
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
var badge = body.data.badge; const badge = body.data.badge;
installations.forEach((installation) => { installations.forEach((installation) => {
expect(installation.badge).toEqual(badge); expect(installation.badge).toEqual(badge);
expect(installation.originalBadge + 1).toEqual(installation.badge); expect(installation.originalBadge + 1).toEqual(installation.badge);
@@ -181,11 +181,11 @@ describe('PushController', () => {
return ["ios", "android"]; return ["ios", "android"];
} }
} }
var payload = {data:{ const payload = {data:{
alert: "Hello World!", alert: "Hello World!",
badge: "Increment", badge: "Increment",
}} }}
var installations = []; const installations = [];
while(installations.length != 10) { while(installations.length != 10) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -205,12 +205,12 @@ describe('PushController', () => {
installation.set("deviceType", "android"); installation.set("deviceType", "android");
installations.push(installation); installations.push(installation);
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
@@ -234,7 +234,7 @@ describe('PushController', () => {
return query.find({ useMasterKey: true }) return query.find({ useMasterKey: true })
}).then((results) => { }).then((results) => {
expect(results.length).toBe(15); expect(results.length).toBe(15);
for (var i = 0; i < 15; i++) { for (let i = 0; i < 15; i++) {
const installation = results[i]; const installation = results[i];
expect(installation.get('badge')).toBe(parseInt(installation.get('originalBadge')) + 1); expect(installation.get('badge')).toBe(parseInt(installation.get('originalBadge')) + 1);
} }
@@ -247,9 +247,9 @@ describe('PushController', () => {
it('properly set badges to 1', (done) => { it('properly set badges to 1', (done) => {
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
var badge = body.data.badge; const badge = body.data.badge;
installations.forEach((installation) => { installations.forEach((installation) => {
expect(installation.badge).toEqual(badge); expect(installation.badge).toEqual(badge);
expect(1).toEqual(installation.badge); expect(1).toEqual(installation.badge);
@@ -261,13 +261,13 @@ describe('PushController', () => {
} }
} }
var payload = {data: { const payload = {data: {
alert: "Hello World!", alert: "Hello World!",
badge: 1, badge: 1,
}} }}
var installations = []; const installations = [];
while(installations.length != 10) { while(installations.length != 10) {
var installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
installation.set("deviceToken","device_token_" + installations.length) installation.set("deviceToken","device_token_" + installations.length)
installation.set("badge", installations.length); installation.set("badge", installations.length);
@@ -276,12 +276,12 @@ describe('PushController', () => {
installations.push(installation); installations.push(installation);
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
@@ -305,7 +305,7 @@ describe('PushController', () => {
return query.find({ useMasterKey: true }) return query.find({ useMasterKey: true })
}).then((results) => { }).then((results) => {
expect(results.length).toBe(10); expect(results.length).toBe(10);
for (var i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
const installation = results[i]; const installation = results[i];
expect(installation.get('badge')).toBe(1); expect(installation.get('badge')).toBe(1);
} }
@@ -318,15 +318,15 @@ describe('PushController', () => {
it('properly set badges to 1 with complex query #2903 #3022', (done) => { it('properly set badges to 1 with complex query #2903 #3022', (done) => {
var payload = { const payload = {
data: { data: {
alert: "Hello World!", alert: "Hello World!",
badge: 1, badge: 1,
} }
} }
var installations = []; const installations = [];
while(installations.length != 10) { while(installations.length != 10) {
var installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
installation.set("deviceToken","device_token_" + installations.length) installation.set("deviceToken","device_token_" + installations.length)
installation.set("badge", installations.length); installation.set("badge", installations.length);
@@ -335,10 +335,10 @@ describe('PushController', () => {
installations.push(installation); installations.push(installation);
} }
let matchedInstallationsCount = 0; let matchedInstallationsCount = 0;
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
matchedInstallationsCount += installations.length; matchedInstallationsCount += installations.length;
var badge = body.data.badge; const badge = body.data.badge;
installations.forEach((installation) => { installations.forEach((installation) => {
expect(installation.badge).toEqual(badge); expect(installation.badge).toEqual(badge);
expect(1).toEqual(installation.badge); expect(1).toEqual(installation.badge);
@@ -350,11 +350,11 @@ describe('PushController', () => {
} }
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { push: {
adapter: pushAdapter adapter: pushAdapter
@@ -393,7 +393,7 @@ describe('PushController', () => {
}; };
const spy = spyOn(pushStatusAfterSave, 'handler').and.callThrough(); const spy = spyOn(pushStatusAfterSave, 'handler').and.callThrough();
Parse.Cloud.afterSave('_PushStatus', pushStatusAfterSave.handler); Parse.Cloud.afterSave('_PushStatus', pushStatusAfterSave.handler);
var installations = []; const installations = [];
while(installations.length != 10) { while(installations.length != 10) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -411,12 +411,12 @@ describe('PushController', () => {
installation.set("deviceType", "android"); installation.set("deviceType", "android");
installations.push(installation); installations.push(installation);
} }
var payload = {data: { const payload = {data: {
alert: "Hello World!", alert: "Hello World!",
badge: 1, badge: 1,
}} }}
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
return successfulIOS(body, installations); return successfulIOS(body, installations);
}, },
@@ -425,11 +425,11 @@ describe('PushController', () => {
} }
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
@@ -515,12 +515,12 @@ describe('PushController', () => {
installation.set("originalBadge", 0); installation.set("originalBadge", 0);
installation.set("deviceType", "ios"); installation.set("deviceType", "ios");
var payload = {data: { const payload = {data: {
alert: "Hello World!", alert: "Hello World!",
badge: 1, badge: 1,
}} }}
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
return successfulIOS(body, installations); return successfulIOS(body, installations);
}, },
@@ -529,11 +529,11 @@ describe('PushController', () => {
} }
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushController = new PushController(); const pushController = new PushController();
return installation.save().then(() => { return installation.save().then(() => {
return reconfigureServer({ return reconfigureServer({
serverURL: 'http://localhost:8378/', // server with borked URL serverURL: 'http://localhost:8378/', // server with borked URL
@@ -560,7 +560,7 @@ describe('PushController', () => {
}); });
it('should properly report failures in _PushStatus', (done) => { it('should properly report failures in _PushStatus', (done) => {
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
return installations.map((installation) => { return installations.map((installation) => {
return Promise.resolve({ return Promise.resolve({
@@ -575,15 +575,15 @@ describe('PushController', () => {
const where = { 'channels': { const where = { 'channels': {
'$ins': ['Giants', 'Mets'] '$ins': ['Giants', 'Mets']
}}; }};
var payload = {data: { const payload = {data: {
alert: "Hello World!", alert: "Hello World!",
badge: 1, badge: 1,
}} }}
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
@@ -603,12 +603,12 @@ describe('PushController', () => {
}); });
it('should support full RESTQuery for increment', (done) => { it('should support full RESTQuery for increment', (done) => {
var payload = {data: { const payload = {data: {
alert: "Hello World!", alert: "Hello World!",
badge: 'Increment', badge: 'Increment',
}} }}
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
return successfulTransmissions(body, installations); return successfulTransmissions(body, installations);
}, },
@@ -616,8 +616,8 @@ describe('PushController', () => {
return ["ios"]; return ["ios"];
} }
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
@@ -627,11 +627,11 @@ describe('PushController', () => {
} }
} }
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
var installations = []; const installations = [];
while (installations.length != 5) { while (installations.length != 5) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -662,13 +662,13 @@ describe('PushController', () => {
}); });
it('should support object type for alert', (done) => { it('should support object type for alert', (done) => {
var payload = {data: { const payload = {data: {
alert: { alert: {
'loc-key': 'hello_world', 'loc-key': 'hello_world',
}, },
}} }}
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
return successfulTransmissions(body, installations); return successfulTransmissions(body, installations);
}, },
@@ -677,8 +677,8 @@ describe('PushController', () => {
} }
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
@@ -686,11 +686,11 @@ describe('PushController', () => {
'deviceType': 'ios' 'deviceType': 'ios'
} }
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
var installations = []; const installations = [];
while (installations.length != 5) { while (installations.length != 5) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -721,7 +721,7 @@ describe('PushController', () => {
}); });
it('should flatten', () => { it('should flatten', () => {
var res = StatusHandler.flatten([1, [2], [[3, 4], 5], [[[6]]]]) const res = StatusHandler.flatten([1, [2], [[3, 4], 5], [[[6]]]])
expect(res).toEqual([1,2,3,4,5,6]); expect(res).toEqual([1,2,3,4,5,6]);
}); });
@@ -762,11 +762,11 @@ describe('PushController', () => {
}); });
it('should not schedule push when not configured', (done) => { it('should not schedule push when not configured', (done) => {
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
return successfulTransmissions(body, installations); return successfulTransmissions(body, installations);
}, },
@@ -775,7 +775,7 @@ describe('PushController', () => {
} }
} }
var pushController = new PushController(); const pushController = new PushController();
const payload = { const payload = {
data: { data: {
alert: 'hello', alert: 'hello',
@@ -783,7 +783,7 @@ describe('PushController', () => {
push_time: new Date().getTime() push_time: new Date().getTime()
} }
var installations = []; const installations = [];
while(installations.length != 10) { while(installations.length != 10) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -816,10 +816,10 @@ describe('PushController', () => {
}); });
it('should schedule push when configured', (done) => { it('should schedule push when configured', (done) => {
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
const promises = installations.map((device) => { const promises = installations.map((device) => {
if (!device.deviceToken) { if (!device.deviceToken) {
@@ -839,7 +839,7 @@ describe('PushController', () => {
} }
} }
var pushController = new PushController(); const pushController = new PushController();
const payload = { const payload = {
data: { data: {
alert: 'hello', alert: 'hello',
@@ -847,7 +847,7 @@ describe('PushController', () => {
push_time: new Date().getTime() / 1000 push_time: new Date().getTime() / 1000
} }
var installations = []; const installations = [];
while(installations.length != 10) { while(installations.length != 10) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -862,7 +862,7 @@ describe('PushController', () => {
push: { adapter: pushAdapter }, push: { adapter: pushAdapter },
scheduledPush: true scheduledPush: true
}).then(() => { }).then(() => {
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
return Parse.Object.saveAll(installations).then(() => { return Parse.Object.saveAll(installations).then(() => {
return pushController.sendPush(payload, {}, config, auth); return pushController.sendPush(payload, {}, config, auth);
}).then(() => new Promise(resolve => setTimeout(resolve, 300))); }).then(() => new Promise(resolve => setTimeout(resolve, 300)));
@@ -877,10 +877,10 @@ describe('PushController', () => {
}); });
it('should not enqueue push when device token is not set', (done) => { it('should not enqueue push when device token is not set', (done) => {
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
const promises = installations.map((device) => { const promises = installations.map((device) => {
if (!device.deviceToken) { if (!device.deviceToken) {
@@ -900,7 +900,7 @@ describe('PushController', () => {
} }
} }
var pushController = new PushController(); const pushController = new PushController();
const payload = { const payload = {
data: { data: {
alert: 'hello', alert: 'hello',
@@ -908,7 +908,7 @@ describe('PushController', () => {
push_time: new Date().getTime() / 1000 push_time: new Date().getTime() / 1000
} }
var installations = []; const installations = [];
while(installations.length != 5) { while(installations.length != 5) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -931,7 +931,7 @@ describe('PushController', () => {
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
return Parse.Object.saveAll(installations).then(() => { return Parse.Object.saveAll(installations).then(() => {
return pushController.sendPush(payload, {}, config, auth); return pushController.sendPush(payload, {}, config, auth);
}).then(() => new Promise(resolve => setTimeout(resolve, 100))); }).then(() => new Promise(resolve => setTimeout(resolve, 100)));
@@ -952,10 +952,10 @@ describe('PushController', () => {
}); });
it('should not mark the _PushStatus as failed when audience has no deviceToken', (done) => { it('should not mark the _PushStatus as failed when audience has no deviceToken', (done) => {
var auth = { const auth = {
isMaster: true isMaster: true
} }
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
const promises = installations.map((device) => { const promises = installations.map((device) => {
if (!device.deviceToken) { if (!device.deviceToken) {
@@ -975,7 +975,7 @@ describe('PushController', () => {
} }
} }
var pushController = new PushController(); const pushController = new PushController();
const payload = { const payload = {
data: { data: {
alert: 'hello', alert: 'hello',
@@ -983,7 +983,7 @@ describe('PushController', () => {
push_time: new Date().getTime() / 1000 push_time: new Date().getTime() / 1000
} }
var installations = []; const installations = [];
while(installations.length != 5) { while(installations.length != 5) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -996,7 +996,7 @@ describe('PushController', () => {
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
return Parse.Object.saveAll(installations).then(() => { return Parse.Object.saveAll(installations).then(() => {
return pushController.sendPush(payload, {}, config, auth) return pushController.sendPush(payload, {}, config, auth)
}).then(() => new Promise(resolve => setTimeout(resolve, 100))); }).then(() => new Promise(resolve => setTimeout(resolve, 100)));
@@ -1017,13 +1017,13 @@ describe('PushController', () => {
}); });
it('should support localized payload data', (done) => { it('should support localized payload data', (done) => {
var payload = {data: { const payload = {data: {
alert: 'Hello!', alert: 'Hello!',
'alert-fr': 'Bonjour', 'alert-fr': 'Bonjour',
'alert-es': 'Ola' 'alert-es': 'Ola'
}} }}
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
return successfulTransmissions(body, installations); return successfulTransmissions(body, installations);
}, },
@@ -1032,8 +1032,8 @@ describe('PushController', () => {
} }
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
@@ -1041,11 +1041,11 @@ describe('PushController', () => {
'deviceType': 'ios' 'deviceType': 'ios'
} }
spyOn(pushAdapter, 'send').and.callThrough(); spyOn(pushAdapter, 'send').and.callThrough();
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
var installations = []; const installations = [];
while (installations.length != 5) { while (installations.length != 5) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -1083,7 +1083,7 @@ describe('PushController', () => {
}); });
it('should update audiences', (done) => { it('should update audiences', (done) => {
var pushAdapter = { const pushAdapter = {
send: function(body, installations) { send: function(body, installations) {
return successfulTransmissions(body, installations); return successfulTransmissions(body, installations);
}, },
@@ -1092,24 +1092,24 @@ describe('PushController', () => {
} }
} }
var config = Config.get(Parse.applicationId); const config = Config.get(Parse.applicationId);
var auth = { const auth = {
isMaster: true isMaster: true
} }
var audienceId = null; let audienceId = null;
var now = new Date(); const now = new Date();
var timesUsed = 0; let timesUsed = 0;
const where = { const where = {
'deviceType': 'ios' 'deviceType': 'ios'
} }
spyOn(pushAdapter, 'send').and.callThrough(); spyOn(pushAdapter, 'send').and.callThrough();
var pushController = new PushController(); const pushController = new PushController();
reconfigureServer({ reconfigureServer({
push: { adapter: pushAdapter } push: { adapter: pushAdapter }
}).then(() => { }).then(() => {
var installations = []; const installations = [];
while (installations.length != 5) { while (installations.length != 5) {
const installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
@@ -1141,7 +1141,7 @@ describe('PushController', () => {
return query.find({ useMasterKey: true }).then(parseResults); return query.find({ useMasterKey: true }).then(parseResults);
}); });
}).then(() => { }).then(() => {
var body = { const body = {
data: { alert: 'hello' }, data: { alert: 'hello' },
audience_id: audienceId audience_id: audienceId
} }

View File

@@ -1,16 +1,16 @@
var PushRouter = require('../src/Routers/PushRouter').PushRouter; const PushRouter = require('../src/Routers/PushRouter').PushRouter;
var request = require('request'); const request = require('request');
describe('PushRouter', () => { describe('PushRouter', () => {
it('can get query condition when channels is set', (done) => { it('can get query condition when channels is set', (done) => {
// Make mock request // Make mock request
var request = { const request = {
body: { body: {
channels: ['Giants', 'Mets'] channels: ['Giants', 'Mets']
} }
} }
var where = PushRouter.getQueryCondition(request); const where = PushRouter.getQueryCondition(request);
expect(where).toEqual({ expect(where).toEqual({
'channels': { 'channels': {
'$in': ['Giants', 'Mets'] '$in': ['Giants', 'Mets']
@@ -21,7 +21,7 @@ describe('PushRouter', () => {
it('can get query condition when where is set', (done) => { it('can get query condition when where is set', (done) => {
// Make mock request // Make mock request
var request = { const request = {
body: { body: {
'where': { 'where': {
'injuryReports': true 'injuryReports': true
@@ -29,7 +29,7 @@ describe('PushRouter', () => {
} }
} }
var where = PushRouter.getQueryCondition(request); const where = PushRouter.getQueryCondition(request);
expect(where).toEqual({ expect(where).toEqual({
'injuryReports': true 'injuryReports': true
}); });
@@ -38,7 +38,7 @@ describe('PushRouter', () => {
it('can get query condition when nothing is set', (done) => { it('can get query condition when nothing is set', (done) => {
// Make mock request // Make mock request
var request = { const request = {
body: { body: {
} }
} }
@@ -51,7 +51,7 @@ describe('PushRouter', () => {
it('can throw on getQueryCondition when channels and where are set', (done) => { it('can throw on getQueryCondition when channels and where are set', (done) => {
// Make mock request // Make mock request
var request = { const request = {
body: { body: {
'channels': { 'channels': {
'$in': ['Giants', 'Mets'] '$in': ['Giants', 'Mets']

View File

@@ -1,13 +1,13 @@
var PushWorker = require('../src').PushWorker; const PushWorker = require('../src').PushWorker;
var PushUtils = require('../src/Push/utils'); const PushUtils = require('../src/Push/utils');
var Config = require('../src/Config'); const Config = require('../src/Config');
var { pushStatusHandler } = require('../src/StatusHandler'); const { pushStatusHandler } = require('../src/StatusHandler');
var rest = require('../src/rest'); const rest = require('../src/rest');
describe('PushWorker', () => { describe('PushWorker', () => {
it('should run with small batch', (done) => { it('should run with small batch', (done) => {
const batchSize = 3; const batchSize = 3;
var sendCount = 0; let sendCount = 0;
reconfigureServer({ reconfigureServer({
push: { push: {
queueOptions: { queueOptions: {
@@ -27,9 +27,9 @@ describe('PushWorker', () => {
return ['ios', 'android'] return ['ios', 'android']
} }
}); });
var installations = []; const installations = [];
while(installations.length != 10) { while(installations.length != 10) {
var installation = new Parse.Object("_Installation"); const installation = new Parse.Object("_Installation");
installation.set("installationId", "installation_" + installations.length); installation.set("installationId", "installation_" + installations.length);
installation.set("deviceToken","device_token_" + installations.length) installation.set("deviceToken","device_token_" + installations.length)
installation.set("badge", 1); installation.set("badge", 1);
@@ -164,7 +164,7 @@ describe('PushWorker', () => {
const config = Config.get('test'); const config = Config.get('test');
const handler = pushStatusHandler(config); const handler = pushStatusHandler(config);
const spy = spyOn(config.database, "update").and.callFake(() => { const spy = spyOn(config.database, "update").and.callFake(() => {
return Promise.resolve(); return Promise.resolve({});
}); });
const toAwait = handler.trackSent([ const toAwait = handler.trackSent([
{ {

View File

@@ -1,27 +1,27 @@
var Parse = require('parse/node'); const Parse = require('parse/node');
var Id = require('../src/LiveQuery/Id'); const Id = require('../src/LiveQuery/Id');
var QueryTools = require('../src/LiveQuery/QueryTools'); const QueryTools = require('../src/LiveQuery/QueryTools');
var queryHash = QueryTools.queryHash; const queryHash = QueryTools.queryHash;
var matchesQuery = QueryTools.matchesQuery; const matchesQuery = QueryTools.matchesQuery;
var Item = Parse.Object.extend('Item'); const Item = Parse.Object.extend('Item');
describe('queryHash', function() { describe('queryHash', function() {
it('should always hash a query to the same string', function() { it('should always hash a query to the same string', function() {
var q = new Parse.Query(Item); const q = new Parse.Query(Item);
q.equalTo('field', 'value'); q.equalTo('field', 'value');
q.exists('name'); q.exists('name');
q.ascending('createdAt'); q.ascending('createdAt');
q.limit(10); q.limit(10);
var firstHash = queryHash(q); const firstHash = queryHash(q);
var secondHash = queryHash(q); const secondHash = queryHash(q);
expect(firstHash).toBe(secondHash); expect(firstHash).toBe(secondHash);
}); });
it('should return equivalent hashes for equivalent queries', function() { it('should return equivalent hashes for equivalent queries', function() {
var q1 = new Parse.Query(Item); let q1 = new Parse.Query(Item);
q1.equalTo('field', 'value'); q1.equalTo('field', 'value');
q1.exists('name'); q1.exists('name');
q1.lessThan('age', 30); q1.lessThan('age', 30);
@@ -30,7 +30,7 @@ describe('queryHash', function() {
q1.include(['name', 'age']); q1.include(['name', 'age']);
q1.limit(10); q1.limit(10);
var q2 = new Parse.Query(Item); let q2 = new Parse.Query(Item);
q2.limit(10); q2.limit(10);
q2.greaterThan('age', 3); q2.greaterThan('age', 3);
q2.lessThan('age', 30); q2.lessThan('age', 30);
@@ -39,8 +39,8 @@ describe('queryHash', function() {
q2.exists('name'); q2.exists('name');
q2.equalTo('field', 'value'); q2.equalTo('field', 'value');
var firstHash = queryHash(q1); let firstHash = queryHash(q1);
var secondHash = queryHash(q2); let secondHash = queryHash(q2);
expect(firstHash).toBe(secondHash); expect(firstHash).toBe(secondHash);
q1.containedIn('fruit', ['apple', 'banana', 'cherry']); q1.containedIn('fruit', ['apple', 'banana', 'cherry']);
@@ -70,10 +70,10 @@ describe('queryHash', function() {
}); });
it('should not let fields of different types appear similar', function() { it('should not let fields of different types appear similar', function() {
var q1 = new Parse.Query(Item); let q1 = new Parse.Query(Item);
q1.lessThan('age', 30); q1.lessThan('age', 30);
var q2 = new Parse.Query(Item); const q2 = new Parse.Query(Item);
q2.equalTo('age', '{$lt:30}'); q2.equalTo('age', '{$lt:30}');
expect(queryHash(q1)).not.toBe(queryHash(q2)); expect(queryHash(q1)).not.toBe(queryHash(q2));
@@ -89,11 +89,11 @@ describe('queryHash', function() {
describe('matchesQuery', function() { describe('matchesQuery', function() {
it('matches blanket queries', function() { it('matches blanket queries', function() {
var obj = { const obj = {
id: new Id('Klass', 'O1'), id: new Id('Klass', 'O1'),
value: 12 value: 12
}; };
var q = new Parse.Query('Klass'); const q = new Parse.Query('Klass');
expect(matchesQuery(obj, q)).toBe(true); expect(matchesQuery(obj, q)).toBe(true);
obj.id = new Id('Other', 'O1'); obj.id = new Id('Other', 'O1');
@@ -101,11 +101,11 @@ describe('matchesQuery', function() {
}); });
it('matches existence queries', function() { it('matches existence queries', function() {
var obj = { const obj = {
id: new Id('Item', 'O1'), id: new Id('Item', 'O1'),
count: 15 count: 15
}; };
var q = new Parse.Query('Item'); const q = new Parse.Query('Item');
q.exists('count'); q.exists('count');
expect(matchesQuery(obj, q)).toBe(true); expect(matchesQuery(obj, q)).toBe(true);
q.exists('name'); q.exists('name');
@@ -113,11 +113,11 @@ describe('matchesQuery', function() {
}); });
it('matches queries with doesNotExist constraint', function() { it('matches queries with doesNotExist constraint', function() {
var obj = { const obj = {
id: new Id('Item', 'O1'), id: new Id('Item', 'O1'),
count: 15 count: 15
}; };
var q = new Parse.Query('Item'); let q = new Parse.Query('Item');
q.doesNotExist('name'); q.doesNotExist('name');
expect(matchesQuery(obj, q)).toBe(true); expect(matchesQuery(obj, q)).toBe(true);
@@ -127,12 +127,12 @@ describe('matchesQuery', function() {
}); });
it('matches on equality queries', function() { it('matches on equality queries', function() {
var day = new Date(); const day = new Date();
var location = new Parse.GeoPoint({ const location = new Parse.GeoPoint({
latitude: 37.484815, latitude: 37.484815,
longitude: -122.148377 longitude: -122.148377
}); });
var obj = { const obj = {
id: new Id('Person', 'O1'), id: new Id('Person', 'O1'),
score: 12, score: 12,
name: 'Bill', name: 'Bill',
@@ -140,7 +140,7 @@ describe('matchesQuery', function() {
lastLocation: location lastLocation: location
}; };
var q = new Parse.Query('Person'); let q = new Parse.Query('Person');
q.equalTo('score', 12); q.equalTo('score', 12);
expect(matchesQuery(obj, q)).toBe(true); expect(matchesQuery(obj, q)).toBe(true);
@@ -192,7 +192,7 @@ describe('matchesQuery', function() {
q.equalTo('name', 'bill'); q.equalTo('name', 'bill');
expect(matchesQuery(obj, q)).toBe(false); expect(matchesQuery(obj, q)).toBe(false);
var img = { let img = {
id: new Id('Image', 'I1'), id: new Id('Image', 'I1'),
tags: ['nofilter', 'latergram', 'tbt'] tags: ['nofilter', 'latergram', 'tbt']
}; };
@@ -203,13 +203,13 @@ describe('matchesQuery', function() {
q.equalTo('tags', 'tbt'); q.equalTo('tags', 'tbt');
expect(matchesQuery(img, q)).toBe(true); expect(matchesQuery(img, q)).toBe(true);
var q2 = new Parse.Query('Image'); const q2 = new Parse.Query('Image');
q2.containsAll('tags', ['latergram', 'nofilter']); q2.containsAll('tags', ['latergram', 'nofilter']);
expect(matchesQuery(img, q2)).toBe(true); expect(matchesQuery(img, q2)).toBe(true);
q2.containsAll('tags', ['latergram', 'selfie']); q2.containsAll('tags', ['latergram', 'selfie']);
expect(matchesQuery(img, q2)).toBe(false); expect(matchesQuery(img, q2)).toBe(false);
var u = new Parse.User(); const u = new Parse.User();
u.id = 'U2'; u.id = 'U2';
q = new Parse.Query('Image'); q = new Parse.Query('Image');
q.equalTo('owner', u); q.equalTo('owner', u);
@@ -246,13 +246,13 @@ describe('matchesQuery', function() {
}); });
it('matches on inequalities', function() { it('matches on inequalities', function() {
var player = { const player = {
id: new Id('Person', 'O1'), id: new Id('Person', 'O1'),
score: 12, score: 12,
name: 'Bill', name: 'Bill',
birthday: new Date(1980, 2, 4), birthday: new Date(1980, 2, 4),
}; };
var q = new Parse.Query('Person'); let q = new Parse.Query('Person');
q.lessThan('score', 15); q.lessThan('score', 15);
expect(matchesQuery(player, q)).toBe(true); expect(matchesQuery(player, q)).toBe(true);
q.lessThan('score', 10); q.lessThan('score', 10);
@@ -288,29 +288,29 @@ describe('matchesQuery', function() {
}); });
it('matches an $or query', function() { it('matches an $or query', function() {
var player = { const player = {
id: new Id('Player', 'P1'), id: new Id('Player', 'P1'),
name: 'Player 1', name: 'Player 1',
score: 12 score: 12
}; };
var q = new Parse.Query('Player'); const q = new Parse.Query('Player');
q.equalTo('name', 'Player 1'); q.equalTo('name', 'Player 1');
var q2 = new Parse.Query('Player'); const q2 = new Parse.Query('Player');
q2.equalTo('name', 'Player 2'); q2.equalTo('name', 'Player 2');
var orQuery = Parse.Query.or(q, q2); const orQuery = Parse.Query.or(q, q2);
expect(matchesQuery(player, q)).toBe(true); expect(matchesQuery(player, q)).toBe(true);
expect(matchesQuery(player, q2)).toBe(false); expect(matchesQuery(player, q2)).toBe(false);
expect(matchesQuery(player, orQuery)).toBe(true); expect(matchesQuery(player, orQuery)).toBe(true);
}); });
it('matches $regex queries', function() { it('matches $regex queries', function() {
var player = { const player = {
id: new Id('Player', 'P1'), id: new Id('Player', 'P1'),
name: 'Player 1', name: 'Player 1',
score: 12 score: 12
}; };
var q = new Parse.Query('Player'); let q = new Parse.Query('Player');
q.startsWith('name', 'Play'); q.startsWith('name', 'Play');
expect(matchesQuery(player, q)).toBe(true); expect(matchesQuery(player, q)).toBe(true);
q.startsWith('name', 'Ploy'); q.startsWith('name', 'Ploy');
@@ -353,17 +353,17 @@ describe('matchesQuery', function() {
}); });
it('matches $nearSphere queries', function() { it('matches $nearSphere queries', function() {
var q = new Parse.Query('Checkin'); let q = new Parse.Query('Checkin');
q.near('location', new Parse.GeoPoint(20, 20)); q.near('location', new Parse.GeoPoint(20, 20));
// With no max distance, any GeoPoint is 'near' // With no max distance, any GeoPoint is 'near'
var pt = { const pt = {
id: new Id('Checkin', 'C1'), id: new Id('Checkin', 'C1'),
location: new Parse.GeoPoint(40, 40) location: new Parse.GeoPoint(40, 40)
}; };
var ptUndefined = { const ptUndefined = {
id: new Id('Checkin', 'C1') id: new Id('Checkin', 'C1')
}; };
var ptNull = { const ptNull = {
id: new Id('Checkin', 'C1'), id: new Id('Checkin', 'C1'),
location: null location: null
}; };
@@ -381,30 +381,30 @@ describe('matchesQuery', function() {
}); });
it('matches $within queries', function() { it('matches $within queries', function() {
var caltrainStation = { const caltrainStation = {
id: new Id('Checkin', 'C1'), id: new Id('Checkin', 'C1'),
location: new Parse.GeoPoint(37.776346, -122.394218), location: new Parse.GeoPoint(37.776346, -122.394218),
name: 'Caltrain' name: 'Caltrain'
}; };
var santaClara = { const santaClara = {
id: new Id('Checkin', 'C2'), id: new Id('Checkin', 'C2'),
location: new Parse.GeoPoint(37.325635, -121.945753), location: new Parse.GeoPoint(37.325635, -121.945753),
name: 'Santa Clara' name: 'Santa Clara'
}; };
var noLocation = { const noLocation = {
id: new Id('Checkin', 'C2'), id: new Id('Checkin', 'C2'),
name: 'Santa Clara' name: 'Santa Clara'
}; };
var nullLocation = { const nullLocation = {
id: new Id('Checkin', 'C2'), id: new Id('Checkin', 'C2'),
location: null, location: null,
name: 'Santa Clara' name: 'Santa Clara'
}; };
var q = new Parse.Query('Checkin').withinGeoBox( let q = new Parse.Query('Checkin').withinGeoBox(
'location', 'location',
new Parse.GeoPoint(37.708813, -122.526398), new Parse.GeoPoint(37.708813, -122.526398),
new Parse.GeoPoint(37.822802, -122.373962) new Parse.GeoPoint(37.822802, -122.373962)
@@ -435,13 +435,13 @@ describe('matchesQuery', function() {
}); });
it('matches on subobjects with dot notation', function() { it('matches on subobjects with dot notation', function() {
var message = { const message = {
id: new Id('Message', 'O1'), id: new Id('Message', 'O1'),
text: "content", text: "content",
status: {x: "read", y: "delivered"} status: {x: "read", y: "delivered"}
}; };
var q = new Parse.Query('Message'); let q = new Parse.Query('Message');
q.equalTo("status.x", "read"); q.equalTo("status.x", "read");
expect(matchesQuery(message, q)).toBe(true); expect(matchesQuery(message, q)).toBe(true);
@@ -501,11 +501,11 @@ describe('matchesQuery', function() {
} }
it('should support containedIn with pointers', () => { it('should support containedIn with pointers', () => {
var message = { const message = {
id: new Id('Message', 'O1'), id: new Id('Message', 'O1'),
profile: pointer('Profile', 'abc') profile: pointer('Profile', 'abc')
}; };
var q = new Parse.Query('Message'); let q = new Parse.Query('Message');
q.containedIn('profile', [Parse.Object.fromJSON({ className: 'Profile', objectId: 'abc' }), q.containedIn('profile', [Parse.Object.fromJSON({ className: 'Profile', objectId: 'abc' }),
Parse.Object.fromJSON({ className: 'Profile', objectId: 'def' })]); Parse.Object.fromJSON({ className: 'Profile', objectId: 'def' })]);
expect(matchesQuery(message, q)).toBe(true); expect(matchesQuery(message, q)).toBe(true);
@@ -517,11 +517,11 @@ describe('matchesQuery', function() {
}); });
it('should support notContainedIn with pointers', () => { it('should support notContainedIn with pointers', () => {
var message = { let message = {
id: new Id('Message', 'O1'), id: new Id('Message', 'O1'),
profile: pointer('Profile', 'abc') profile: pointer('Profile', 'abc')
}; };
var q = new Parse.Query('Message'); let q = new Parse.Query('Message');
q.notContainedIn('profile', [Parse.Object.fromJSON({ className: 'Profile', objectId: 'def' }), q.notContainedIn('profile', [Parse.Object.fromJSON({ className: 'Profile', objectId: 'def' }),
Parse.Object.fromJSON({ className: 'Profile', objectId: 'ghi' })]); Parse.Object.fromJSON({ className: 'Profile', objectId: 'ghi' })]);
expect(matchesQuery(message, q)).toBe(true); expect(matchesQuery(message, q)).toBe(true);
@@ -537,11 +537,11 @@ describe('matchesQuery', function() {
}); });
it('should support containedIn queries with [objectId]', () => { it('should support containedIn queries with [objectId]', () => {
var message = { let message = {
id: new Id('Message', 'O1'), id: new Id('Message', 'O1'),
profile: pointer('Profile', 'abc') profile: pointer('Profile', 'abc')
}; };
var q = new Parse.Query('Message'); let q = new Parse.Query('Message');
q.containedIn('profile', ['abc', 'def']); q.containedIn('profile', ['abc', 'def']);
expect(matchesQuery(message, q)).toBe(true); expect(matchesQuery(message, q)).toBe(true);
@@ -555,11 +555,11 @@ describe('matchesQuery', function() {
}); });
it('should support notContainedIn queries with [objectId]', () => { it('should support notContainedIn queries with [objectId]', () => {
var message = { let message = {
id: new Id('Message', 'O1'), id: new Id('Message', 'O1'),
profile: pointer('Profile', 'ghi') profile: pointer('Profile', 'ghi')
}; };
var q = new Parse.Query('Message'); let q = new Parse.Query('Message');
q.notContainedIn('profile', ['abc', 'def']); q.notContainedIn('profile', ['abc', 'def']);
expect(matchesQuery(message, q)).toBe(true); expect(matchesQuery(message, q)).toBe(true);
message = { message = {

View File

@@ -1,4 +1,4 @@
var RedisCacheAdapter = require('../src/Adapters/Cache/RedisCacheAdapter').default; const RedisCacheAdapter = require('../src/Adapters/Cache/RedisCacheAdapter').default;
/* /*
To run this test part of the complete suite To run this test part of the complete suite
set PARSE_SERVER_TEST_CACHE='redis' set PARSE_SERVER_TEST_CACHE='redis'
@@ -7,8 +7,8 @@ and make sure a redis server is available on the default port
describe_only(() => { describe_only(() => {
return process.env.PARSE_SERVER_TEST_CACHE === 'redis'; return process.env.PARSE_SERVER_TEST_CACHE === 'redis';
})('RedisCacheAdapter', function() { })('RedisCacheAdapter', function() {
var KEY = 'hello'; const KEY = 'hello';
var VALUE = 'world'; const VALUE = 'world';
function wait(sleep) { function wait(sleep) {
return new Promise(function(resolve) { return new Promise(function(resolve) {
@@ -17,7 +17,7 @@ describe_only(() => {
} }
it('should get/set/clear', (done) => { it('should get/set/clear', (done) => {
var cache = new RedisCacheAdapter({ const cache = new RedisCacheAdapter({
ttl: NaN ttl: NaN
}); });
@@ -31,7 +31,7 @@ describe_only(() => {
}); });
it('should expire after ttl', (done) => { it('should expire after ttl', (done) => {
var cache = new RedisCacheAdapter(null, 1); const cache = new RedisCacheAdapter(null, 1);
cache.put(KEY, VALUE) cache.put(KEY, VALUE)
.then(() => cache.get(KEY)) .then(() => cache.get(KEY))
@@ -43,7 +43,7 @@ describe_only(() => {
}); });
it('should find un-expired records', (done) => { it('should find un-expired records', (done) => {
var cache = new RedisCacheAdapter(null, 5); const cache = new RedisCacheAdapter(null, 5);
cache.put(KEY, VALUE) cache.put(KEY, VALUE)
.then(() => cache.get(KEY)) .then(() => cache.get(KEY))

View File

@@ -1,10 +1,10 @@
var RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub; const RedisPubSub = require('../src/Adapters/PubSub/RedisPubSub').RedisPubSub;
describe('RedisPubSub', function() { describe('RedisPubSub', function() {
beforeEach(function(done) { beforeEach(function(done) {
// Mock redis // Mock redis
var createClient = jasmine.createSpy('createClient'); const createClient = jasmine.createSpy('createClient');
jasmine.mockLibrary('redis', 'createClient', createClient); jasmine.mockLibrary('redis', 'createClient', createClient);
done(); done();
}); });
@@ -12,14 +12,14 @@ describe('RedisPubSub', function() {
it('can create publisher', function() { it('can create publisher', function() {
RedisPubSub.createPublisher({redisURL: 'redisAddress'}); RedisPubSub.createPublisher({redisURL: 'redisAddress'});
var redis = require('redis'); const redis = require('redis');
expect(redis.createClient).toHaveBeenCalledWith('redisAddress', { no_ready_check: true }); expect(redis.createClient).toHaveBeenCalledWith('redisAddress', { no_ready_check: true });
}); });
it('can create subscriber', function() { it('can create subscriber', function() {
RedisPubSub.createSubscriber({redisURL: 'redisAddress'}); RedisPubSub.createSubscriber({redisURL: 'redisAddress'});
var redis = require('redis'); const redis = require('redis');
expect(redis.createClient).toHaveBeenCalledWith('redisAddress', { no_ready_check: true }); expect(redis.createClient).toHaveBeenCalledWith('redisAddress', { no_ready_check: true });
}); });

View File

@@ -1,15 +1,15 @@
'use strict' 'use strict'
// These tests check the "find" functionality of the REST API. // These tests check the "find" functionality of the REST API.
var auth = require('../src/Auth'); const auth = require('../src/Auth');
var Config = require('../src/Config'); const Config = require('../src/Config');
var rest = require('../src/rest'); const rest = require('../src/rest');
var querystring = require('querystring'); const querystring = require('querystring');
var rp = require('request-promise'); const rp = require('request-promise');
var config; let config;
let database; let database;
var nobody = auth.nobody(config); const nobody = auth.nobody(config);
describe('rest query', () => { describe('rest query', () => {
@@ -42,7 +42,7 @@ describe('rest query', () => {
}); });
}); });
var data = { const data = {
username: 'blah', username: 'blah',
password: 'pass', password: 'pass',
sessionToken: 'abc123', sessionToken: 'abc123',
@@ -52,7 +52,7 @@ describe('rest query', () => {
database.create('_User', data).then(() => { database.create('_User', data).then(() => {
return rest.find(config, nobody, '_User') return rest.find(config, nobody, '_User')
}).then((result) => { }).then((result) => {
var user = result.results[0]; const user = result.results[0];
expect(user.username).toEqual('blah'); expect(user.username).toEqual('blah');
expect(user.sessionToken).toBeUndefined(); expect(user.sessionToken).toBeUndefined();
expect(user.password).toBeUndefined(); expect(user.password).toBeUndefined();
@@ -64,7 +64,7 @@ describe('rest query', () => {
database.create('_User', data).then(() => { database.create('_User', data).then(() => {
return rest.find(config, {isMaster: true}, '_User') return rest.find(config, {isMaster: true}, '_User')
}).then((result) => { }).then((result) => {
var user = result.results[0]; const user = result.results[0];
expect(user.username).toEqual('blah'); expect(user.username).toEqual('blah');
expect(user.sessionToken).toBeUndefined(); expect(user.sessionToken).toBeUndefined();
expect(user.password).toBeUndefined(); expect(user.password).toBeUndefined();
@@ -74,14 +74,14 @@ describe('rest query', () => {
// Created to test a scenario in AnyPic // Created to test a scenario in AnyPic
it_exclude_dbs(['postgres'])('query with include', (done) => { it_exclude_dbs(['postgres'])('query with include', (done) => {
var photo = { let photo = {
foo: 'bar' foo: 'bar'
}; };
var user = { let user = {
username: 'aUsername', username: 'aUsername',
password: 'aPassword' password: 'aPassword'
}; };
var activity = { const activity = {
type: 'comment', type: 'comment',
photo: { photo: {
__type: 'Pointer', __type: 'Pointer',
@@ -94,7 +94,7 @@ describe('rest query', () => {
objectId: '' objectId: ''
} }
}; };
var queryWhere = { const queryWhere = {
photo: { photo: {
__type: 'Pointer', __type: 'Pointer',
className: 'TestPhoto', className: 'TestPhoto',
@@ -102,7 +102,7 @@ describe('rest query', () => {
}, },
type: 'comment' type: 'comment'
}; };
var queryOptions = { const queryOptions = {
include: 'fromUser', include: 'fromUser',
order: 'createdAt', order: 'createdAt',
limit: 30 limit: 30
@@ -122,7 +122,7 @@ describe('rest query', () => {
return rest.find(config, nobody, return rest.find(config, nobody,
'TestActivity', queryWhere, queryOptions); 'TestActivity', queryWhere, queryOptions);
}).then((response) => { }).then((response) => {
var results = response.results; const results = response.results;
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
expect(typeof results[0].objectId).toEqual('string'); expect(typeof results[0].objectId).toEqual('string');
expect(typeof results[0].photo).toEqual('object'); expect(typeof results[0].photo).toEqual('object');
@@ -133,7 +133,7 @@ describe('rest query', () => {
}); });
it('query non-existent class when disabled client class creation', (done) => { it('query non-existent class when disabled client class creation', (done) => {
var customConfig = Object.assign({}, config, {allowClientClassCreation: false}); const customConfig = Object.assign({}, config, {allowClientClassCreation: false});
rest.find(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}) rest.find(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {})
.then(() => { .then(() => {
fail('Should throw an error'); fail('Should throw an error');
@@ -147,7 +147,7 @@ describe('rest query', () => {
}); });
it('query existent class when disabled client class creation', (done) => { it('query existent class when disabled client class creation', (done) => {
var customConfig = Object.assign({}, config, {allowClientClassCreation: false}); const customConfig = Object.assign({}, config, {allowClientClassCreation: false});
config.database.loadSchema() config.database.loadSchema()
.then(schema => schema.addClassIfNotExists('ClientClassCreation', {})) .then(schema => schema.addClassIfNotExists('ClientClassCreation', {}))
.then(actualSchema => { .then(actualSchema => {
@@ -168,7 +168,7 @@ describe('rest query', () => {
return rest.create(config, nobody, return rest.create(config, nobody,
'TestParameterEncode', {foo: 'baz'}); 'TestParameterEncode', {foo: 'baz'});
}).then(() => { }).then(() => {
var headers = { const headers = {
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
}; };
@@ -182,7 +182,7 @@ describe('rest query', () => {
}) })
.then(fail, (response) => { .then(fail, (response) => {
const error = response.error; const error = response.error;
var b = JSON.parse(error); const b = JSON.parse(error);
expect(b.code).toEqual(Parse.Error.INVALID_QUERY); expect(b.code).toEqual(Parse.Error.INVALID_QUERY);
}); });
@@ -194,7 +194,7 @@ describe('rest query', () => {
}) })
.then(fail, (response) => { .then(fail, (response) => {
const error = response.error; const error = response.error;
var b = JSON.parse(error); const b = JSON.parse(error);
expect(b.code).toEqual(Parse.Error.INVALID_QUERY); expect(b.code).toEqual(Parse.Error.INVALID_QUERY);
}); });
return Promise.all([p0, p1]); return Promise.all([p0, p1]);

View File

@@ -1,13 +1,13 @@
'use strict'; 'use strict';
var Config = require('../src/Config'); const Config = require('../src/Config');
var SchemaController = require('../src/Controllers/SchemaController'); const SchemaController = require('../src/Controllers/SchemaController');
var dd = require('deep-diff'); const dd = require('deep-diff');
var config; let config;
var hasAllPODobject = () => { const hasAllPODobject = () => {
var obj = new Parse.Object('HasAllPOD'); const obj = new Parse.Object('HasAllPOD');
obj.set('aNumber', 5); obj.set('aNumber', 5);
obj.set('aString', 'string'); obj.set('aString', 'string');
obj.set('aBool', true); obj.set('aBool', true);
@@ -104,7 +104,7 @@ describe('SchemaController', () => {
'find': {} 'find': {}
}); });
}).then(() => { }).then(() => {
var query = new Parse.Query('Stuff'); const query = new Parse.Query('Stuff');
return query.find(); return query.find();
}).then(() => { }).then(() => {
fail('Class permissions should have rejected this query.'); fail('Class permissions should have rejected this query.');
@@ -115,7 +115,7 @@ describe('SchemaController', () => {
}); });
it('class-level permissions test user', (done) => { it('class-level permissions test user', (done) => {
var user; let user;
createTestUser().then((u) => { createTestUser().then((u) => {
user = u; user = u;
return config.database.loadSchema(); return config.database.loadSchema();
@@ -123,13 +123,13 @@ describe('SchemaController', () => {
// Just to create a valid class // Just to create a valid class
return schema.validateObject('Stuff', {foo: 'bar'}); return schema.validateObject('Stuff', {foo: 'bar'});
}).then((schema) => { }).then((schema) => {
var find = {}; const find = {};
find[user.id] = true; find[user.id] = true;
return schema.setPermissions('Stuff', { return schema.setPermissions('Stuff', {
'find': find 'find': find
}); });
}).then(() => { }).then(() => {
var query = new Parse.Query('Stuff'); const query = new Parse.Query('Stuff');
return query.find(); return query.find();
}).then(() => { }).then(() => {
done(); done();
@@ -140,15 +140,15 @@ describe('SchemaController', () => {
}); });
it('class-level permissions test get', (done) => { it('class-level permissions test get', (done) => {
var obj; let obj;
createTestUser() createTestUser()
.then(user => { .then(user => {
return config.database.loadSchema() return config.database.loadSchema()
// Create a valid class // Create a valid class
.then(schema => schema.validateObject('Stuff', {foo: 'bar'})) .then(schema => schema.validateObject('Stuff', {foo: 'bar'}))
.then(schema => { .then(schema => {
var find = {}; const find = {};
var get = {}; const get = {};
get[user.id] = true; get[user.id] = true;
return schema.setPermissions('Stuff', { return schema.setPermissions('Stuff', {
'create': {'*': true}, 'create': {'*': true},
@@ -161,13 +161,13 @@ describe('SchemaController', () => {
return obj.save(); return obj.save();
}).then((o) => { }).then((o) => {
obj = o; obj = o;
var query = new Parse.Query('Stuff'); const query = new Parse.Query('Stuff');
return query.find(); return query.find();
}).then(() => { }).then(() => {
fail('Class permissions should have rejected this query.'); fail('Class permissions should have rejected this query.');
done(); done();
}, () => { }, () => {
var query = new Parse.Query('Stuff'); const query = new Parse.Query('Stuff');
return query.get(obj.id).then(() => { return query.get(obj.id).then(() => {
done(); done();
}, () => { }, () => {
@@ -179,12 +179,12 @@ describe('SchemaController', () => {
}); });
it('class-level permissions test count', (done) => { it('class-level permissions test count', (done) => {
var obj; let obj;
return config.database.loadSchema() return config.database.loadSchema()
// Create a valid class // Create a valid class
.then(schema => schema.validateObject('Stuff', {foo: 'bar'})) .then(schema => schema.validateObject('Stuff', {foo: 'bar'}))
.then(schema => { .then(schema => {
var count = {}; const count = {};
return schema.setPermissions('Stuff', { return schema.setPermissions('Stuff', {
'create': {'*': true}, 'create': {'*': true},
'find': {'*': true}, 'find': {'*': true},
@@ -196,11 +196,11 @@ describe('SchemaController', () => {
return obj.save(); return obj.save();
}).then((o) => { }).then((o) => {
obj = o; obj = o;
var query = new Parse.Query('Stuff'); const query = new Parse.Query('Stuff');
return query.find(); return query.find();
}).then((results) => { }).then((results) => {
expect(results.length).toBe(1); expect(results.length).toBe(1);
var query = new Parse.Query('Stuff'); const query = new Parse.Query('Stuff');
return query.count(); return query.count();
}).then(() => { }).then(() => {
fail('Class permissions should have rejected this query.'); fail('Class permissions should have rejected this query.');
@@ -341,8 +341,8 @@ describe('SchemaController', () => {
// race loser should be the same as if they hadn't been racing. // race loser should be the same as if they hadn't been racing.
config.database.loadSchema() config.database.loadSchema()
.then(schema => { .then(schema => {
var p1 = schema.addClassIfNotExists('NewClass', {foo: {type: 'String'}}); const p1 = schema.addClassIfNotExists('NewClass', {foo: {type: 'String'}});
var p2 = schema.addClassIfNotExists('NewClass', {foo: {type: 'String'}}); const p2 = schema.addClassIfNotExists('NewClass', {foo: {type: 'String'}});
Promise.race([p1, p2]) Promise.race([p1, p2])
.then(actualSchema => { .then(actualSchema => {
const expectedSchema = { const expectedSchema = {
@@ -758,12 +758,12 @@ describe('SchemaController', () => {
}); });
it('drops related collection when deleting relation field', done => { it('drops related collection when deleting relation field', done => {
var obj1 = hasAllPODobject(); const obj1 = hasAllPODobject();
obj1.save() obj1.save()
.then(savedObj1 => { .then(savedObj1 => {
var obj2 = new Parse.Object('HasPointersAndRelations'); const obj2 = new Parse.Object('HasPointersAndRelations');
obj2.set('aPointer', savedObj1); obj2.set('aPointer', savedObj1);
var relation = obj2.relation('aRelation'); const relation = obj2.relation('aRelation');
relation.add(obj1); relation.add(obj1);
return obj2.save(); return obj2.save();
}) })
@@ -842,8 +842,8 @@ describe('SchemaController', () => {
it('can delete string fields and resave as number field', done => { it('can delete string fields and resave as number field', done => {
Parse.Object.disableSingleInstance(); Parse.Object.disableSingleInstance();
var obj1 = hasAllPODobject(); const obj1 = hasAllPODobject();
var obj2 = hasAllPODobject(); const obj2 = hasAllPODobject();
Parse.Object.saveAll([obj1, obj2]) Parse.Object.saveAll([obj1, obj2])
.then(() => config.database.loadSchema()) .then(() => config.database.loadSchema())
.then(schema => schema.deleteField('aString', 'HasAllPOD', config.database)) .then(schema => schema.deleteField('aString', 'HasAllPOD', config.database))
@@ -870,7 +870,7 @@ describe('SchemaController', () => {
it('can delete pointer fields and resave as string', done => { it('can delete pointer fields and resave as string', done => {
Parse.Object.disableSingleInstance(); Parse.Object.disableSingleInstance();
var obj1 = new Parse.Object('NewClass'); const obj1 = new Parse.Object('NewClass');
obj1.save() obj1.save()
.then(() => { .then(() => {
obj1.set('aPointer', obj1); obj1.set('aPointer', obj1);
@@ -1053,7 +1053,7 @@ describe('Class Level Permissions for requiredAuth', () => {
} }
}); });
}).then(() => { }).then(() => {
var query = new Parse.Query('Stuff'); const query = new Parse.Query('Stuff');
return query.find(); return query.find();
}).then(() => { }).then(() => {
fail('Class permissions should have rejected this query.'); fail('Class permissions should have rejected this query.');
@@ -1077,7 +1077,7 @@ describe('Class Level Permissions for requiredAuth', () => {
}).then(() => { }).then(() => {
return createUser(); return createUser();
}).then(() => { }).then(() => {
var query = new Parse.Query('Stuff'); const query = new Parse.Query('Stuff');
return query.find(); return query.find();
}).then((results) => { }).then((results) => {
expect(results.length).toEqual(0); expect(results.length).toEqual(0);

View File

@@ -1,6 +1,6 @@
var CacheController = require('../src/Controllers/CacheController.js').default; const CacheController = require('../src/Controllers/CacheController.js').default;
var InMemoryCacheAdapter = require('../src/Adapters/Cache/InMemoryCacheAdapter').default; const InMemoryCacheAdapter = require('../src/Adapters/Cache/InMemoryCacheAdapter').default;
var SchemaCache = require('../src/Controllers/SchemaCache').default; const SchemaCache = require('../src/Controllers/SchemaCache').default;
describe('SchemaCache', () => { describe('SchemaCache', () => {
let cacheController; let cacheController;

View File

@@ -1,9 +1,9 @@
var SessionTokenCache = require('../src/LiveQuery/SessionTokenCache').SessionTokenCache; const SessionTokenCache = require('../src/LiveQuery/SessionTokenCache').SessionTokenCache;
describe('SessionTokenCache', function() { describe('SessionTokenCache', function() {
beforeEach(function(done) { beforeEach(function(done) {
var Parse = require('parse/node'); const Parse = require('parse/node');
spyOn(Parse, "Query").and.returnValue({ spyOn(Parse, "Query").and.returnValue({
first: jasmine.createSpy("first").and.returnValue(Parse.Promise.as(new Parse.Object("_Session", { first: jasmine.createSpy("first").and.returnValue(Parse.Promise.as(new Parse.Object("_Session", {
@@ -16,7 +16,7 @@ describe('SessionTokenCache', function() {
}); });
it('can get undefined userId', function(done) { it('can get undefined userId', function(done) {
var sessionTokenCache = new SessionTokenCache(); const sessionTokenCache = new SessionTokenCache();
sessionTokenCache.getUserId(undefined).then(() => { sessionTokenCache.getUserId(undefined).then(() => {
}, (error) => { }, (error) => {
@@ -26,9 +26,9 @@ describe('SessionTokenCache', function() {
}); });
it('can get existing userId', function(done) { it('can get existing userId', function(done) {
var sessionTokenCache = new SessionTokenCache(); const sessionTokenCache = new SessionTokenCache();
var sessionToken = 'sessionToken'; const sessionToken = 'sessionToken';
var userId = 'userId' const userId = 'userId'
sessionTokenCache.cache.set(sessionToken, userId); sessionTokenCache.cache.set(sessionToken, userId);
sessionTokenCache.getUserId(sessionToken).then((userIdFromCache) => { sessionTokenCache.getUserId(sessionToken).then((userIdFromCache) => {
@@ -38,7 +38,7 @@ describe('SessionTokenCache', function() {
}); });
it('can get new userId', function(done) { it('can get new userId', function(done) {
var sessionTokenCache = new SessionTokenCache(); const sessionTokenCache = new SessionTokenCache();
sessionTokenCache.getUserId('sessionToken').then((userIdFromCache) => { sessionTokenCache.getUserId('sessionToken').then((userIdFromCache) => {
expect(userIdFromCache).toBe('userId'); expect(userIdFromCache).toBe('userId');

View File

@@ -1,4 +1,4 @@
var Subscription = require('../src/LiveQuery/Subscription').Subscription; const Subscription = require('../src/LiveQuery/Subscription').Subscription;
let logger; let logger;
describe('Subscription', function() { describe('Subscription', function() {
@@ -8,7 +8,7 @@ describe('Subscription', function() {
}); });
it('can be initialized', function() { it('can be initialized', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
expect(subscription.className).toBe('className'); expect(subscription.className).toBe('className');
expect(subscription.query).toEqual({ key : 'value' }); expect(subscription.query).toEqual({ key : 'value' });
@@ -17,20 +17,20 @@ describe('Subscription', function() {
}); });
it('can check it has subscribing clients', function() { it('can check it has subscribing clients', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
expect(subscription.hasSubscribingClient()).toBe(false); expect(subscription.hasSubscribingClient()).toBe(false);
}); });
it('can check it does not have subscribing clients', function() { it('can check it does not have subscribing clients', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 1);
expect(subscription.hasSubscribingClient()).toBe(true); expect(subscription.hasSubscribingClient()).toBe(true);
}); });
it('can add one request for one client', function() { it('can add one request for one client', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 1);
expect(subscription.clientRequestIds.size).toBe(1); expect(subscription.clientRequestIds.size).toBe(1);
@@ -38,7 +38,7 @@ describe('Subscription', function() {
}); });
it('can add requests for one client', function() { it('can add requests for one client', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 1);
subscription.addClientSubscription(1, 2); subscription.addClientSubscription(1, 2);
@@ -47,7 +47,7 @@ describe('Subscription', function() {
}); });
it('can add requests for clients', function() { it('can add requests for clients', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 1);
subscription.addClientSubscription(1, 2); subscription.addClientSubscription(1, 2);
subscription.addClientSubscription(2, 2); subscription.addClientSubscription(2, 2);
@@ -59,14 +59,14 @@ describe('Subscription', function() {
}); });
it('can delete requests for nonexistent client', function() { it('can delete requests for nonexistent client', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.deleteClientSubscription(1, 1); subscription.deleteClientSubscription(1, 1);
expect(logger.error).toHaveBeenCalled(); expect(logger.error).toHaveBeenCalled();
}); });
it('can delete nonexistent request for one client', function() { it('can delete nonexistent request for one client', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 1);
subscription.deleteClientSubscription(1, 2); subscription.deleteClientSubscription(1, 2);
@@ -76,7 +76,7 @@ describe('Subscription', function() {
}); });
it('can delete some requests for one client', function() { it('can delete some requests for one client', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 1);
subscription.addClientSubscription(1, 2); subscription.addClientSubscription(1, 2);
subscription.deleteClientSubscription(1, 2); subscription.deleteClientSubscription(1, 2);
@@ -87,7 +87,7 @@ describe('Subscription', function() {
}); });
it('can delete all requests for one client', function() { it('can delete all requests for one client', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 1);
subscription.addClientSubscription(1, 2); subscription.addClientSubscription(1, 2);
subscription.deleteClientSubscription(1, 1); subscription.deleteClientSubscription(1, 1);
@@ -98,7 +98,7 @@ describe('Subscription', function() {
}); });
it('can delete requests for multiple clients', function() { it('can delete requests for multiple clients', function() {
var subscription = new Subscription('className', { key : 'value' }, 'hash'); const subscription = new Subscription('className', { key : 'value' }, 'hash');
subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 1);
subscription.addClientSubscription(1, 2); subscription.addClientSubscription(1, 2);
subscription.addClientSubscription(2, 1); subscription.addClientSubscription(2, 1);

View File

@@ -1,9 +1,9 @@
var UserController = require('../src/Controllers/UserController').UserController; const UserController = require('../src/Controllers/UserController').UserController;
var emailAdapter = require('./MockEmailAdapter') const emailAdapter = require('./MockEmailAdapter')
var AppCache = require('../src/cache').AppCache; const AppCache = require('../src/cache').AppCache;
describe('UserController', () => { describe('UserController', () => {
var user = { const user = {
_email_verify_token: 'testToken', _email_verify_token: 'testToken',
username: 'testUser', username: 'testUser',
email: 'test@example.com' email: 'test@example.com'
@@ -25,7 +25,7 @@ describe('UserController', () => {
done() done()
} }
var userController = new UserController(emailAdapter, 'test', { const userController = new UserController(emailAdapter, 'test', {
verifyUserEmails: true verifyUserEmails: true
}) })
@@ -48,7 +48,7 @@ describe('UserController', () => {
done() done()
} }
var userController = new UserController(emailAdapter, 'test', { const userController = new UserController(emailAdapter, 'test', {
verifyUserEmails: true verifyUserEmails: true
}) })

View File

@@ -18,7 +18,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
publicServerURL: "https://my.public.server.com/1" publicServerURL: "https://my.public.server.com/1"
}) })
.then(() => { .then(() => {
var config = Config.get("test"); const config = Config.get("test");
expect(config.invalidLinkURL).toEqual("myInvalidLink"); expect(config.invalidLinkURL).toEqual("myInvalidLink");
expect(config.verifyEmailSuccessURL).toEqual("myVerifyEmailSuccess"); expect(config.verifyEmailSuccessURL).toEqual("myVerifyEmailSuccess");
expect(config.choosePasswordURL).toEqual("myChoosePassword"); expect(config.choosePasswordURL).toEqual("myChoosePassword");
@@ -31,7 +31,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('sends verification email if email verification is enabled', done => { it('sends verification email if email verification is enabled', done => {
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: () => Promise.resolve(), sendVerificationEmail: () => Promise.resolve(),
sendPasswordResetEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(),
sendMail: () => Promise.resolve() sendMail: () => Promise.resolve()
@@ -44,7 +44,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}) })
.then(() => { .then(() => {
spyOn(emailAdapter, 'sendVerificationEmail'); spyOn(emailAdapter, 'sendVerificationEmail');
var user = new Parse.User(); const user = new Parse.User();
user.setPassword("asdf"); user.setPassword("asdf");
user.setUsername("zxcv"); user.setUsername("zxcv");
user.setEmail('testIfEnabled@parse.com'); user.setEmail('testIfEnabled@parse.com');
@@ -66,7 +66,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('does not send verification email when verification is enabled and email is not set', done => { it('does not send verification email when verification is enabled and email is not set', done => {
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: () => Promise.resolve(), sendVerificationEmail: () => Promise.resolve(),
sendPasswordResetEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(),
sendMail: () => Promise.resolve() sendMail: () => Promise.resolve()
@@ -79,7 +79,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}) })
.then(() => { .then(() => {
spyOn(emailAdapter, 'sendVerificationEmail'); spyOn(emailAdapter, 'sendVerificationEmail');
var user = new Parse.User(); const user = new Parse.User();
user.setPassword("asdf"); user.setPassword("asdf");
user.setUsername("zxcv"); user.setUsername("zxcv");
user.signUp(null, { user.signUp(null, {
@@ -100,7 +100,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('does send a validation email when updating the email', done => { it('does send a validation email when updating the email', done => {
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: () => Promise.resolve(), sendVerificationEmail: () => Promise.resolve(),
sendPasswordResetEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(),
sendMail: () => Promise.resolve() sendMail: () => Promise.resolve()
@@ -113,7 +113,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}) })
.then(() => { .then(() => {
spyOn(emailAdapter, 'sendVerificationEmail'); spyOn(emailAdapter, 'sendVerificationEmail');
var user = new Parse.User(); const user = new Parse.User();
user.setPassword("asdf"); user.setPassword("asdf");
user.setUsername("zxcv"); user.setUsername("zxcv");
user.signUp(null, { user.signUp(null, {
@@ -143,7 +143,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('does send a validation email with valid verification link when updating the email', done => { it('does send a validation email with valid verification link when updating the email', done => {
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: () => Promise.resolve(), sendVerificationEmail: () => Promise.resolve(),
sendPasswordResetEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(),
sendMail: () => Promise.resolve() sendMail: () => Promise.resolve()
@@ -160,7 +160,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
expect(options.link).not.toMatch(/token=undefined/); expect(options.link).not.toMatch(/token=undefined/);
Promise.resolve(); Promise.resolve();
}); });
var user = new Parse.User(); const user = new Parse.User();
user.setPassword("asdf"); user.setPassword("asdf");
user.setUsername("zxcv"); user.setUsername("zxcv");
user.signUp(null, { user.signUp(null, {
@@ -190,8 +190,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('does send with a simple adapter', done => { it('does send with a simple adapter', done => {
var calls = 0; let calls = 0;
var emailAdapter = { const emailAdapter = {
sendMail: function(options){ sendMail: function(options){
expect(options.to).toBe('testSendSimpleAdapter@parse.com'); expect(options.to).toBe('testSendSimpleAdapter@parse.com');
if (calls == 0) { if (calls == 0) {
@@ -212,7 +212,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
publicServerURL: "http://localhost:8378/1" publicServerURL: "http://localhost:8378/1"
}) })
.then(() => { .then(() => {
var user = new Parse.User(); const user = new Parse.User();
user.setPassword("asdf"); user.setPassword("asdf");
user.setUsername("zxcv"); user.setUsername("zxcv");
user.set("email", "testSendSimpleAdapter@parse.com"); user.set("email", "testSendSimpleAdapter@parse.com");
@@ -277,9 +277,9 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('allows user to login only after user clicks on the link to confirm email address if preventLoginWithUnverifiedEmail is set to true', done => { it('allows user to login only after user clicks on the link to confirm email address if preventLoginWithUnverifiedEmail is set to true', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -524,7 +524,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('does not send verification email if email verification is disabled', done => { it('does not send verification email if email verification is disabled', done => {
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: () => Promise.resolve(), sendVerificationEmail: () => Promise.resolve(),
sendPasswordResetEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(),
sendMail: () => Promise.resolve() sendMail: () => Promise.resolve()
@@ -537,7 +537,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}) })
.then(() => { .then(() => {
spyOn(emailAdapter, 'sendVerificationEmail'); spyOn(emailAdapter, 'sendVerificationEmail');
var user = new Parse.User(); const user = new Parse.User();
user.setPassword("asdf"); user.setPassword("asdf");
user.setUsername("zxcv"); user.setUsername("zxcv");
user.signUp(null, { user.signUp(null, {
@@ -558,8 +558,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('receives the app name and user in the adapter', done => { it('receives the app name and user in the adapter', done => {
var emailSent = false; let emailSent = false;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
expect(options.appName).toEqual('emailing app'); expect(options.appName).toEqual('emailing app');
expect(options.user.get('email')).toEqual('user@parse.com'); expect(options.user.get('email')).toEqual('user@parse.com');
@@ -575,7 +575,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
publicServerURL: "http://localhost:8378/1" publicServerURL: "http://localhost:8378/1"
}) })
.then(() => { .then(() => {
var user = new Parse.User(); const user = new Parse.User();
user.setPassword("asdf"); user.setPassword("asdf");
user.setUsername("zxcv"); user.setUsername("zxcv");
user.set('email', 'user@parse.com'); user.set('email', 'user@parse.com');
@@ -593,9 +593,9 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}) })
it('when you click the link in the email it sets emailVerified to true and redirects you', done => { it('when you click the link in the email it sets emailVerified to true and redirects you', done => {
var user = new Parse.User(); const user = new Parse.User();
var sendEmailOptions; let sendEmailOptions;
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: options => { sendVerificationEmail: options => {
sendEmailOptions = options; sendEmailOptions = options;
}, },
@@ -706,8 +706,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('does not update email verified if you use an invalid token', done => { it('does not update email verified if you use an invalid token', done => {
var user = new Parse.User(); const user = new Parse.User();
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: () => { sendVerificationEmail: () => {
request.get('http://localhost:8378/1/apps/test/verify_email?token=invalid&username=zxcv', { request.get('http://localhost:8378/1/apps/test/verify_email?token=invalid&username=zxcv', {
followRedirect: false, followRedirect: false,
@@ -745,8 +745,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('should send a password reset link', done => { it('should send a password reset link', done => {
var user = new Parse.User(); const user = new Parse.User();
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: () => Promise.resolve(), sendVerificationEmail: () => Promise.resolve(),
sendPasswordResetEmail: options => { sendPasswordResetEmail: options => {
request.get(options.link, { request.get(options.link, {
@@ -758,7 +758,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
return; return;
} }
expect(response.statusCode).toEqual(302); expect(response.statusCode).toEqual(302);
var re = /http:\/\/localhost:8378\/1\/apps\/choose_password\?token=[a-zA-Z0-9]+\&id=test\&username=zxcv%2Bzxcv/; const re = /http:\/\/localhost:8378\/1\/apps\/choose_password\?token=[a-zA-Z0-9]+\&id=test\&username=zxcv%2Bzxcv/;
expect(response.body.match(re)).not.toBe(null); expect(response.body.match(re)).not.toBe(null);
done(); done();
}); });
@@ -810,8 +810,8 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
}); });
it('should programatically reset password', done => { it('should programatically reset password', done => {
var user = new Parse.User(); const user = new Parse.User();
var emailAdapter = { const emailAdapter = {
sendVerificationEmail: () => Promise.resolve(), sendVerificationEmail: () => Promise.resolve(),
sendPasswordResetEmail: options => { sendPasswordResetEmail: options => {
request.get(options.link, { request.get(options.link, {
@@ -823,14 +823,14 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
return; return;
} }
expect(response.statusCode).toEqual(302); expect(response.statusCode).toEqual(302);
var re = /http:\/\/localhost:8378\/1\/apps\/choose_password\?token=([a-zA-Z0-9]+)\&id=test\&username=zxcv/; const re = /http:\/\/localhost:8378\/1\/apps\/choose_password\?token=([a-zA-Z0-9]+)\&id=test\&username=zxcv/;
var match = response.body.match(re); const match = response.body.match(re);
if (!match) { if (!match) {
fail("should have a token"); fail("should have a token");
done(); done();
return; return;
} }
var token = match[1]; const token = match[1];
request.post({ request.post({
url: "http://localhost:8378/1/apps/test/request_password_reset" , url: "http://localhost:8378/1/apps/test/request_password_reset" ,

View File

@@ -1,12 +1,12 @@
'use strict'; 'use strict';
var WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter; const WinstonLoggerAdapter = require('../src/Adapters/Logger/WinstonLoggerAdapter').WinstonLoggerAdapter;
var request = require('request'); const request = require('request');
describe('info logs', () => { describe('info logs', () => {
it("Verify INFO logs", (done) => { it("Verify INFO logs", (done) => {
var winstonLoggerAdapter = new WinstonLoggerAdapter(); const winstonLoggerAdapter = new WinstonLoggerAdapter();
winstonLoggerAdapter.log('info', 'testing info logs', () => { winstonLoggerAdapter.log('info', 'testing info logs', () => {
winstonLoggerAdapter.query({ winstonLoggerAdapter.query({
from: new Date(Date.now() - 500), from: new Date(Date.now() - 500),
@@ -35,7 +35,7 @@ describe('info logs', () => {
describe('error logs', () => { describe('error logs', () => {
it("Verify ERROR logs", (done) => { it("Verify ERROR logs", (done) => {
var winstonLoggerAdapter = new WinstonLoggerAdapter(); const winstonLoggerAdapter = new WinstonLoggerAdapter();
winstonLoggerAdapter.log('error', 'testing error logs', () => { winstonLoggerAdapter.log('error', 'testing error logs', () => {
winstonLoggerAdapter.query({ winstonLoggerAdapter.query({
from: new Date(Date.now() - 500), from: new Date(Date.now() - 500),
@@ -71,7 +71,7 @@ describe('verbose logs', () => {
expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0); expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0);
expect(logString.match(/moon-y/g)).toBe(null); expect(logString.match(/moon-y/g)).toBe(null);
var headers = { const headers = {
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
}; };

View File

@@ -1,4 +1,4 @@
var batch = require('../src/batch'); const batch = require('../src/batch');
const originalURL = '/parse/batch'; const originalURL = '/parse/batch';
const serverURL = 'http://localhost:1234/parse'; const serverURL = 'http://localhost:1234/parse';

View File

@@ -1,9 +1,9 @@
var cryptoUtils = require('../src/cryptoUtils'); const cryptoUtils = require('../src/cryptoUtils');
function givesUniqueResults(fn, iterations) { function givesUniqueResults(fn, iterations) {
var results = {}; const results = {};
for (var i = 0; i < iterations; i++) { for (let i = 0; i < iterations; i++) {
var s = fn(); const s = fn();
if (results[s]) { if (results[s]) {
return false; return false;
} }

View File

@@ -23,10 +23,10 @@ if (global._babelPolyfill) {
process.exit(1); process.exit(1);
} }
var cache = require('../src/cache').default; const cache = require('../src/cache').default;
var ParseServer = require('../src/index').ParseServer; const ParseServer = require('../src/index').ParseServer;
var path = require('path'); const path = require('path');
var TestUtils = require('../src/TestUtils'); const TestUtils = require('../src/TestUtils');
const GridStoreAdapter = require('../src/Adapters/Files/GridStoreAdapter').GridStoreAdapter; const GridStoreAdapter = require('../src/Adapters/Files/GridStoreAdapter').GridStoreAdapter;
const FSAdapter = require('@parse/fs-files-adapter'); const FSAdapter = require('@parse/fs-files-adapter');
import PostgresStorageAdapter from '../src/Adapters/Storage/Postgres/PostgresStorageAdapter'; import PostgresStorageAdapter from '../src/Adapters/Storage/Postgres/PostgresStorageAdapter';
@@ -58,7 +58,7 @@ if (process.env.PARSE_SERVER_TEST_DB === 'postgres') {
}); });
} }
var port = 8378; const port = 8378;
let filesAdapter; let filesAdapter;
@@ -79,7 +79,7 @@ if (process.env.PARSE_SERVER_LOG_LEVEL) {
logLevel = process.env.PARSE_SERVER_LOG_LEVEL; logLevel = process.env.PARSE_SERVER_LOG_LEVEL;
} }
// Default server configuration for tests. // Default server configuration for tests.
var defaultConfiguration = { const defaultConfiguration = {
filesAdapter, filesAdapter,
serverURL: 'http://localhost:' + port + '/1', serverURL: 'http://localhost:' + port + '/1',
databaseAdapter, databaseAdapter,
@@ -116,7 +116,7 @@ if (process.env.PARSE_SERVER_TEST_CACHE === 'redis') {
const openConnections = {}; const openConnections = {};
// Set up a default API server for testing with default configuration. // Set up a default API server for testing with default configuration.
var server; let server;
// Allows testing specific configurations of Parse Server // Allows testing specific configurations of Parse Server
const reconfigureServer = changedConfiguration => { const reconfigureServer = changedConfiguration => {
@@ -153,7 +153,7 @@ const reconfigureServer = changedConfiguration => {
} }
// Set up a Parse client to talk to our test API server // Set up a Parse client to talk to our test API server
var Parse = require('parse/node'); const Parse = require('parse/node');
Parse.serverURL = 'http://localhost:' + port + '/1'; Parse.serverURL = 'http://localhost:' + port + '/1';
// This is needed because we ported a bunch of tests from the non-A+ way. // This is needed because we ported a bunch of tests from the non-A+ way.
@@ -204,7 +204,7 @@ afterEach(function(done) {
databaseAdapter.getAllClasses() databaseAdapter.getAllClasses()
.then(allSchemas => { .then(allSchemas => {
allSchemas.forEach((schema) => { allSchemas.forEach((schema) => {
var className = schema.className; const className = schema.className;
expect(className).toEqual({ asymmetricMatch: className => { expect(className).toEqual({ asymmetricMatch: className => {
if (!className.startsWith('_')) { if (!className.startsWith('_')) {
return true; return true;
@@ -220,27 +220,27 @@ afterEach(function(done) {
.then(afterLogOut, afterLogOut) .then(afterLogOut, afterLogOut)
}); });
var TestObject = Parse.Object.extend({ const TestObject = Parse.Object.extend({
className: "TestObject" className: "TestObject"
}); });
var Item = Parse.Object.extend({ const Item = Parse.Object.extend({
className: "Item" className: "Item"
}); });
var Container = Parse.Object.extend({ const Container = Parse.Object.extend({
className: "Container" className: "Container"
}); });
// Convenience method to create a new TestObject with a callback // Convenience method to create a new TestObject with a callback
function create(options, callback) { function create(options, callback) {
var t = new TestObject(options); const t = new TestObject(options);
t.save(null, { success: callback }); t.save(null, { success: callback });
} }
function createTestUser(success, error) { function createTestUser(success, error) {
var user = new Parse.User(); const user = new Parse.User();
user.set('username', 'test'); user.set('username', 'test');
user.set('password', 'moon-y'); user.set('password', 'moon-y');
var promise = user.signUp(); const promise = user.signUp();
if (success || error) { if (success || error) {
promise.then(function(user) { promise.then(function(user) {
if (success) { if (success) {
@@ -312,8 +312,8 @@ function normalize(obj) {
if (obj instanceof Array) { if (obj instanceof Array) {
return '[' + obj.map(normalize).join(', ') + ']'; return '[' + obj.map(normalize).join(', ') + ']';
} }
var answer = '{'; let answer = '{';
for (var key of Object.keys(obj).sort()) { for (const key of Object.keys(obj).sort()) {
answer += key + ': '; answer += key + ': ';
answer += normalize(obj[key]); answer += normalize(obj[key]);
answer += ', '; answer += ', ';
@@ -328,15 +328,15 @@ function jequal(o1, o2) {
} }
function range(n) { function range(n) {
var answer = []; const answer = [];
for (var i = 0; i < n; i++) { for (let i = 0; i < n; i++) {
answer.push(i); answer.push(i);
} }
return answer; return answer;
} }
function mockFacebookAuthenticator(id, token) { function mockFacebookAuthenticator(id, token) {
var facebook = {}; const facebook = {};
facebook.validateAuthData = function(authData) { facebook.validateAuthData = function(authData) {
if (authData.id === id && authData.access_token.startsWith(token)) { if (authData.id === id && authData.access_token.startsWith(token)) {
return Promise.resolve(); return Promise.resolve();
@@ -444,9 +444,9 @@ global.describe_only = (validator) =>{
}; };
var libraryCache = {}; const libraryCache = {};
jasmine.mockLibrary = function(library, name, mock) { jasmine.mockLibrary = function(library, name, mock) {
var original = require(library)[name]; const original = require(library)[name];
if (!libraryCache[library]) { if (!libraryCache[library]) {
libraryCache[library] = {}; libraryCache[library] = {};
} }

View File

@@ -1,10 +1,10 @@
"use strict" "use strict"
var request = require('request'); const request = require('request');
var parseServerPackage = require('../package.json'); const parseServerPackage = require('../package.json');
var MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions'); const MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions');
var ParseServer = require("../src/index"); const ParseServer = require("../src/index");
var Config = require('../src/Config'); const Config = require('../src/Config');
var express = require('express'); const express = require('express');
import MongoStorageAdapter from '../src/Adapters/Storage/Mongo/MongoStorageAdapter'; import MongoStorageAdapter from '../src/Adapters/Storage/Mongo/MongoStorageAdapter';
@@ -270,7 +270,7 @@ describe('server', () => {
}); });
it('can create a parse-server v1', done => { it('can create a parse-server v1', done => {
var parseServer = new ParseServer.default(Object.assign({}, const parseServer = new ParseServer.default(Object.assign({},
defaultConfiguration, { defaultConfiguration, {
appId: "aTestApp", appId: "aTestApp",
masterKey: "aTestMasterKey", masterKey: "aTestMasterKey",
@@ -279,15 +279,15 @@ describe('server', () => {
promise promise
.then(() => { .then(() => {
expect(Parse.applicationId).toEqual("aTestApp"); expect(Parse.applicationId).toEqual("aTestApp");
var app = express(); const app = express();
app.use('/parse', parseServer.app); app.use('/parse', parseServer.app);
var server = app.listen(12666); const server = app.listen(12666);
var obj = new Parse.Object("AnObject"); const obj = new Parse.Object("AnObject");
var objId; let objId;
obj.save().then((obj) => { obj.save().then((obj) => {
objId = obj.id; objId = obj.id;
var q = new Parse.Query("AnObject"); const q = new Parse.Query("AnObject");
return q.first(); return q.first();
}).then((obj) => { }).then((obj) => {
expect(obj.id).toEqual(objId); expect(obj.id).toEqual(objId);
@@ -360,7 +360,7 @@ describe('server', () => {
it('properly gives publicServerURL when set', done => { it('properly gives publicServerURL when set', done => {
reconfigureServer({ publicServerURL: 'https://myserver.com/1' }) reconfigureServer({ publicServerURL: 'https://myserver.com/1' })
.then(() => { .then(() => {
var config = Config.get('test', 'http://localhost:8378/1'); const config = Config.get('test', 'http://localhost:8378/1');
expect(config.mount).toEqual('https://myserver.com/1'); expect(config.mount).toEqual('https://myserver.com/1');
done(); done();
}); });
@@ -369,7 +369,7 @@ describe('server', () => {
it('properly removes trailing slash in mount', done => { it('properly removes trailing slash in mount', done => {
reconfigureServer({}) reconfigureServer({})
.then(() => { .then(() => {
var config = Config.get('test', 'http://localhost:8378/1/'); const config = Config.get('test', 'http://localhost:8378/1/');
expect(config.mount).toEqual('http://localhost:8378/1'); expect(config.mount).toEqual('http://localhost:8378/1');
done(); done();
}); });

View File

@@ -1,12 +1,12 @@
"use strict"; "use strict";
// These tests check the "create" / "update" functionality of the REST API. // These tests check the "create" / "update" functionality of the REST API.
var auth = require('../src/Auth'); const auth = require('../src/Auth');
var Config = require('../src/Config'); const Config = require('../src/Config');
var Parse = require('parse/node').Parse; const Parse = require('parse/node').Parse;
var rest = require('../src/rest'); const rest = require('../src/rest');
var RestWrite = require('../src/RestWrite'); const RestWrite = require('../src/RestWrite');
var request = require('request'); const request = require('request');
var rp = require('request-promise'); const rp = require('request-promise');
let config; let config;
let database; let database;
@@ -23,7 +23,7 @@ describe('rest create', () => {
.then(() => database.adapter.find('Foo', { fields: {} }, {}, {})) .then(() => database.adapter.find('Foo', { fields: {} }, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(typeof obj.objectId).toEqual('string'); expect(typeof obj.objectId).toEqual('string');
expect(obj.objectId.length).toEqual(10); expect(obj.objectId.length).toEqual(10);
expect(obj._id).toBeUndefined(); expect(obj._id).toBeUndefined();
@@ -37,7 +37,7 @@ describe('rest create', () => {
.then(() => database.adapter.find('Foo', { fields: {} }, {}, {})) .then(() => database.adapter.find('Foo', { fields: {} }, {}, {}))
.then((results) => { .then((results) => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var obj = results[0]; const obj = results[0];
expect(typeof obj.objectId).toEqual('string'); expect(typeof obj.objectId).toEqual('string');
expect(obj.objectId.length).toEqual(20); expect(obj.objectId.length).toEqual(20);
done(); done();
@@ -76,7 +76,7 @@ describe('rest create', () => {
it('handles array, object, date', (done) => { it('handles array, object, date', (done) => {
const now = new Date(); const now = new Date();
var obj = { const obj = {
array: [1, 2, 3], array: [1, 2, 3],
object: {foo: 'bar'}, object: {foo: 'bar'},
date: Parse._encode(now), date: Parse._encode(now),
@@ -89,7 +89,7 @@ describe('rest create', () => {
} }, {}, {})) } }, {}, {}))
.then(results => { .then(results => {
expect(results.length).toEqual(1); expect(results.length).toEqual(1);
var mob = results[0]; const mob = results[0];
expect(mob.array instanceof Array).toBe(true); expect(mob.array instanceof Array).toBe(true);
expect(typeof mob.object).toBe('object'); expect(typeof mob.object).toBe('object');
expect(mob.date.__type).toBe('Date'); expect(mob.date.__type).toBe('Date');
@@ -135,7 +135,7 @@ describe('rest create', () => {
}); });
it('handles create on non-existent class when disabled client class creation', (done) => { it('handles create on non-existent class when disabled client class creation', (done) => {
var customConfig = Object.assign({}, config, {allowClientClassCreation: false}); const customConfig = Object.assign({}, config, {allowClientClassCreation: false});
rest.create(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}) rest.create(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {})
.then(() => { .then(() => {
fail('Should throw an error'); fail('Should throw an error');
@@ -149,7 +149,7 @@ describe('rest create', () => {
}); });
it('handles create on existent class when disabled client class creation', (done) => { it('handles create on existent class when disabled client class creation', (done) => {
var customConfig = Object.assign({}, config, {allowClientClassCreation: false}); const customConfig = Object.assign({}, config, {allowClientClassCreation: false});
config.database.loadSchema() config.database.loadSchema()
.then(schema => schema.addClassIfNotExists('ClientClassCreation', {})) .then(schema => schema.addClassIfNotExists('ClientClassCreation', {}))
.then(actualSchema => { .then(actualSchema => {
@@ -164,7 +164,7 @@ describe('rest create', () => {
}); });
it('handles user signup', (done) => { it('handles user signup', (done) => {
var user = { const user = {
username: 'asdf', username: 'asdf',
password: 'zxcv', password: 'zxcv',
foo: 'bar', foo: 'bar',
@@ -180,21 +180,21 @@ describe('rest create', () => {
}); });
it('handles anonymous user signup', (done) => { it('handles anonymous user signup', (done) => {
var data1 = { const data1 = {
authData: { authData: {
anonymous: { anonymous: {
id: '00000000-0000-0000-0000-000000000001' id: '00000000-0000-0000-0000-000000000001'
} }
} }
}; };
var data2 = { const data2 = {
authData: { authData: {
anonymous: { anonymous: {
id: '00000000-0000-0000-0000-000000000002' id: '00000000-0000-0000-0000-000000000002'
} }
} }
}; };
var username1; let username1;
rest.create(config, auth.nobody(config), '_User', data1) rest.create(config, auth.nobody(config), '_User', data1)
.then((r) => { .then((r) => {
expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.objectId).toEqual('string');
@@ -225,7 +225,7 @@ describe('rest create', () => {
}); });
it('handles anonymous user signup and upgrade to new user', (done) => { it('handles anonymous user signup and upgrade to new user', (done) => {
var data1 = { const data1 = {
authData: { authData: {
anonymous: { anonymous: {
id: '00000000-0000-0000-0000-000000000001' id: '00000000-0000-0000-0000-000000000001'
@@ -233,12 +233,12 @@ describe('rest create', () => {
} }
}; };
var updatedData = { const updatedData = {
authData: { anonymous: null }, authData: { anonymous: null },
username: 'hello', username: 'hello',
password: 'world' password: 'world'
} }
var objectId; let objectId;
rest.create(config, auth.nobody(config), '_User', data1) rest.create(config, auth.nobody(config), '_User', data1)
.then((r) => { .then((r) => {
expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.objectId).toEqual('string');
@@ -263,9 +263,9 @@ describe('rest create', () => {
}); });
it('handles no anonymous users config', (done) => { it('handles no anonymous users config', (done) => {
var NoAnnonConfig = Object.assign({}, config); const NoAnnonConfig = Object.assign({}, config);
NoAnnonConfig.authDataManager.setEnableAnonymousUsers(false); NoAnnonConfig.authDataManager.setEnableAnonymousUsers(false);
var data1 = { const data1 = {
authData: { authData: {
anonymous: { anonymous: {
id: '00000000-0000-0000-0000-000000000001' id: '00000000-0000-0000-0000-000000000001'
@@ -284,7 +284,7 @@ describe('rest create', () => {
}); });
it('test facebook signup and login', (done) => { it('test facebook signup and login', (done) => {
var data = { const data = {
authData: { authData: {
facebook: { facebook: {
id: '8675309', id: '8675309',
@@ -292,7 +292,7 @@ describe('rest create', () => {
} }
} }
}; };
var newUserSignedUpByFacebookObjectId; let newUserSignedUpByFacebookObjectId;
rest.create(config, auth.nobody(config), '_User', data) rest.create(config, auth.nobody(config), '_User', data)
.then((r) => { .then((r) => {
expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.objectId).toEqual('string');
@@ -310,7 +310,7 @@ describe('rest create', () => {
'_Session', {sessionToken: r.response.sessionToken}); '_Session', {sessionToken: r.response.sessionToken});
}).then((response) => { }).then((response) => {
expect(response.results.length).toEqual(1); expect(response.results.length).toEqual(1);
var output = response.results[0]; const output = response.results[0];
expect(output.user.objectId).toEqual(newUserSignedUpByFacebookObjectId); expect(output.user.objectId).toEqual(newUserSignedUpByFacebookObjectId);
done(); done();
}).catch(err => { }).catch(err => {
@@ -349,7 +349,7 @@ describe('rest create', () => {
}); });
it("cannot set objectId", (done) => { it("cannot set objectId", (done) => {
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest' 'X-Parse-REST-API-Key': 'rest'
@@ -362,7 +362,7 @@ describe('rest create', () => {
'objectId': 'hello' 'objectId': 'hello'
}) })
}, (error, response, body) => { }, (error, response, body) => {
var b = JSON.parse(body); const b = JSON.parse(body);
expect(b.code).toEqual(105); expect(b.code).toEqual(105);
expect(b.error).toEqual('objectId is an invalid field name.'); expect(b.error).toEqual('objectId is an invalid field name.');
done(); done();
@@ -370,12 +370,12 @@ describe('rest create', () => {
}); });
it("test default session length", (done) => { it("test default session length", (done) => {
var user = { const user = {
username: 'asdf', username: 'asdf',
password: 'zxcv', password: 'zxcv',
foo: 'bar', foo: 'bar',
}; };
var now = new Date(); const now = new Date();
rest.create(config, auth.nobody(config), '_User', user) rest.create(config, auth.nobody(config), '_User', user)
.then((r) => { .then((r) => {
@@ -389,9 +389,9 @@ describe('rest create', () => {
.then((r) => { .then((r) => {
expect(r.results.length).toEqual(1); expect(r.results.length).toEqual(1);
var session = r.results[0]; const session = r.results[0];
var actual = new Date(session.expiresAt.iso); const actual = new Date(session.expiresAt.iso);
var expected = new Date(now.getTime() + (1000 * 3600 * 24 * 365)); const expected = new Date(now.getTime() + (1000 * 3600 * 24 * 365));
expect(actual.getFullYear()).toEqual(expected.getFullYear()); expect(actual.getFullYear()).toEqual(expected.getFullYear());
expect(actual.getMonth()).toEqual(expected.getMonth()); expect(actual.getMonth()).toEqual(expected.getMonth());
@@ -404,12 +404,12 @@ describe('rest create', () => {
}); });
it("test specified session length", (done) => { it("test specified session length", (done) => {
var user = { const user = {
username: 'asdf', username: 'asdf',
password: 'zxcv', password: 'zxcv',
foo: 'bar', foo: 'bar',
}; };
var sessionLength = 3600, // 1 Hour ahead const sessionLength = 3600, // 1 Hour ahead
now = new Date(); // For reference later now = new Date(); // For reference later
config.sessionLength = sessionLength; config.sessionLength = sessionLength;
@@ -425,9 +425,9 @@ describe('rest create', () => {
.then((r) => { .then((r) => {
expect(r.results.length).toEqual(1); expect(r.results.length).toEqual(1);
var session = r.results[0]; const session = r.results[0];
var actual = new Date(session.expiresAt.iso); const actual = new Date(session.expiresAt.iso);
var expected = new Date(now.getTime() + (sessionLength * 1000)); const expected = new Date(now.getTime() + (sessionLength * 1000));
expect(actual.getFullYear()).toEqual(expected.getFullYear()); expect(actual.getFullYear()).toEqual(expected.getFullYear());
expect(actual.getMonth()).toEqual(expected.getMonth()); expect(actual.getMonth()).toEqual(expected.getMonth());
@@ -443,7 +443,7 @@ describe('rest create', () => {
}); });
it("can create a session with no expiration", (done) => { it("can create a session with no expiration", (done) => {
var user = { const user = {
username: 'asdf', username: 'asdf',
password: 'zxcv', password: 'zxcv',
foo: 'bar' foo: 'bar'
@@ -462,7 +462,7 @@ describe('rest create', () => {
.then((r) => { .then((r) => {
expect(r.results.length).toEqual(1); expect(r.results.length).toEqual(1);
var session = r.results[0]; const session = r.results[0];
expect(session.expiresAt).toBeUndefined(); expect(session.expiresAt).toBeUndefined();
done(); done();
@@ -491,7 +491,7 @@ describe('rest create', () => {
it("cannot create object in volatileClasses if not masterKey", (done) =>{ it("cannot create object in volatileClasses if not masterKey", (done) =>{
Promise.resolve() Promise.resolve()
.then(() => { .then(() => {
rest.create(config, auth.nobody(config), '_PushStatus', {}) return rest.create(config, auth.nobody(config), '_PushStatus', {})
}) })
.then((r) => { .then((r) => {
console.log(r); console.log(r);
@@ -502,12 +502,12 @@ describe('rest create', () => {
}) })
}); });
it ('locks down session', (done) => { it('locks down session', (done) => {
let currentUser; let currentUser;
Parse.User.signUp('foo', 'bar').then((user) => { Parse.User.signUp('foo', 'bar').then((user) => {
currentUser = user; currentUser = user;
const sessionToken = user.getSessionToken(); const sessionToken = user.getSessionToken();
var headers = { const headers = {
'Content-Type': 'application/octet-stream', 'Content-Type': 'application/octet-stream',
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest', 'X-Parse-REST-API-Key': 'rest',
@@ -599,6 +599,7 @@ describe('rest create', () => {
describe('rest update', () => { describe('rest update', () => {
it('ignores createdAt', done => { it('ignores createdAt', done => {
const config = Config.get('test');
const nobody = auth.nobody(config); const nobody = auth.nobody(config);
const className = 'Foo'; const className = 'Foo';
const newCreatedAt = new Date('1970-01-01T00:00:00.000Z'); const newCreatedAt = new Date('1970-01-01T00:00:00.000Z');
@@ -619,10 +620,7 @@ describe('rest update', () => {
const updatedObject = res2.results[0]; const updatedObject = res2.results[0];
expect(new Date(updatedObject.createdAt)).not.toEqual(newCreatedAt); expect(new Date(updatedObject.createdAt)).not.toEqual(newCreatedAt);
done(); done();
}).then(done).catch(err => { }).then(done).catch(done.fail);
fail(err);
done();
});
}); });
}); });

View File

@@ -1,15 +1,15 @@
'use strict'; 'use strict';
var Parse = require('parse/node').Parse; const Parse = require('parse/node').Parse;
var request = require('request'); const request = require('request');
const rp = require('request-promise'); const rp = require('request-promise');
var dd = require('deep-diff'); const dd = require('deep-diff');
var Config = require('../src/Config'); const Config = require('../src/Config');
var config; let config;
var hasAllPODobject = () => { const hasAllPODobject = () => {
var obj = new Parse.Object('HasAllPOD'); const obj = new Parse.Object('HasAllPOD');
obj.set('aNumber', 5); obj.set('aNumber', 5);
obj.set('aString', 'string'); obj.set('aString', 'string');
obj.set('aBool', true); obj.set('aBool', true);
@@ -18,7 +18,7 @@ var hasAllPODobject = () => {
obj.set('aArray', ['contents', true, 5]); obj.set('aArray', ['contents', true, 5]);
obj.set('aGeoPoint', new Parse.GeoPoint({latitude: 0, longitude: 0})); obj.set('aGeoPoint', new Parse.GeoPoint({latitude: 0, longitude: 0}));
obj.set('aFile', new Parse.File('f.txt', { base64: 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=' })); obj.set('aFile', new Parse.File('f.txt', { base64: 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=' }));
var objACL = new Parse.ACL(); const objACL = new Parse.ACL();
objACL.setPublicWriteAccess(false); objACL.setPublicWriteAccess(false);
obj.setACL(objACL); obj.setACL(objACL);
return obj; return obj;
@@ -45,7 +45,7 @@ const defaultClassLevelPermissions = {
} }
} }
var plainOldDataSchema = { const plainOldDataSchema = {
className: 'HasAllPOD', className: 'HasAllPOD',
fields: { fields: {
//Default fields //Default fields
@@ -66,7 +66,7 @@ var plainOldDataSchema = {
classLevelPermissions: defaultClassLevelPermissions classLevelPermissions: defaultClassLevelPermissions
}; };
var pointersAndRelationsSchema = { const pointersAndRelationsSchema = {
className: 'HasPointersAndRelations', className: 'HasPointersAndRelations',
fields: { fields: {
//Default fields //Default fields
@@ -117,16 +117,16 @@ const roleSchema = {
"classLevelPermissions": defaultClassLevelPermissions, "classLevelPermissions": defaultClassLevelPermissions,
} }
var noAuthHeaders = { const noAuthHeaders = {
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
}; };
var restKeyHeaders = { const restKeyHeaders = {
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest', 'X-Parse-REST-API-Key': 'rest',
}; };
var masterKeyHeaders = { const masterKeyHeaders = {
'X-Parse-Application-Id': 'test', 'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key': 'test', 'X-Parse-Master-Key': 'test',
}; };
@@ -184,7 +184,7 @@ describe('schemas', () => {
json: true, json: true,
headers: masterKeyHeaders, headers: masterKeyHeaders,
}, (error, response, body) => { }, (error, response, body) => {
var expected = { const expected = {
results: [userSchema,roleSchema] results: [userSchema,roleSchema]
}; };
expect(dd(body.results.sort((s1, s2) => s1.className > s2.className), expected.results.sort((s1, s2) => s1.className > s2.className))).toEqual(undefined); expect(dd(body.results.sort((s1, s2) => s1.className > s2.className), expected.results.sort((s1, s2) => s1.className > s2.className))).toEqual(undefined);
@@ -193,11 +193,11 @@ describe('schemas', () => {
}); });
it('responds with a list of schemas after creating objects', done => { it('responds with a list of schemas after creating objects', done => {
var obj1 = hasAllPODobject(); const obj1 = hasAllPODobject();
obj1.save().then(savedObj1 => { obj1.save().then(savedObj1 => {
var obj2 = new Parse.Object('HasPointersAndRelations'); const obj2 = new Parse.Object('HasPointersAndRelations');
obj2.set('aPointer', savedObj1); obj2.set('aPointer', savedObj1);
var relation = obj2.relation('aRelation'); const relation = obj2.relation('aRelation');
relation.add(obj1); relation.add(obj1);
return obj2.save(); return obj2.save();
}).then(() => { }).then(() => {
@@ -206,7 +206,7 @@ describe('schemas', () => {
json: true, json: true,
headers: masterKeyHeaders, headers: masterKeyHeaders,
}, (error, response, body) => { }, (error, response, body) => {
var expected = { const expected = {
results: [userSchema,roleSchema,plainOldDataSchema,pointersAndRelationsSchema] results: [userSchema,roleSchema,plainOldDataSchema,pointersAndRelationsSchema]
}; };
expect(dd(body.results.sort((s1, s2) => s1.className > s2.className), expected.results.sort((s1, s2) => s1.className > s2.className))).toEqual(undefined); expect(dd(body.results.sort((s1, s2) => s1.className > s2.className), expected.results.sort((s1, s2) => s1.className > s2.className))).toEqual(undefined);
@@ -216,7 +216,7 @@ describe('schemas', () => {
}); });
it('responds with a single schema', done => { it('responds with a single schema', done => {
var obj = hasAllPODobject(); const obj = hasAllPODobject();
obj.save().then(() => { obj.save().then(() => {
request.get({ request.get({
url: 'http://localhost:8378/1/schemas/HasAllPOD', url: 'http://localhost:8378/1/schemas/HasAllPOD',
@@ -230,7 +230,7 @@ describe('schemas', () => {
}); });
it('treats class names case sensitively', done => { it('treats class names case sensitively', done => {
var obj = hasAllPODobject(); const obj = hasAllPODobject();
obj.save().then(() => { obj.save().then(() => {
request.get({ request.get({
url: 'http://localhost:8378/1/schemas/HASALLPOD', url: 'http://localhost:8378/1/schemas/HASALLPOD',
@@ -485,7 +485,7 @@ describe('schemas', () => {
}); });
it('refuses to put to existing fields, even if it would not be a change', done => { it('refuses to put to existing fields, even if it would not be a change', done => {
var obj = hasAllPODobject(); const obj = hasAllPODobject();
obj.save() obj.save()
.then(() => { .then(() => {
request.put({ request.put({
@@ -507,7 +507,7 @@ describe('schemas', () => {
}); });
it('refuses to delete non-existent fields', done => { it('refuses to delete non-existent fields', done => {
var obj = hasAllPODobject(); const obj = hasAllPODobject();
obj.save() obj.save()
.then(() => { .then(() => {
request.put({ request.put({
@@ -529,7 +529,7 @@ describe('schemas', () => {
}); });
it('refuses to add a geopoint to a class that already has one', done => { it('refuses to add a geopoint to a class that already has one', done => {
var obj = hasAllPODobject(); const obj = hasAllPODobject();
obj.save() obj.save()
.then(() => { .then(() => {
request.put({ request.put({
@@ -551,7 +551,7 @@ describe('schemas', () => {
}); });
it('refuses to add two geopoints', done => { it('refuses to add two geopoints', done => {
var obj = new Parse.Object('NewClass'); const obj = new Parse.Object('NewClass');
obj.set('aString', 'aString'); obj.set('aString', 'aString');
obj.save() obj.save()
.then(() => { .then(() => {
@@ -575,7 +575,7 @@ describe('schemas', () => {
}); });
it('allows you to delete and add a geopoint in the same request', done => { it('allows you to delete and add a geopoint in the same request', done => {
var obj = new Parse.Object('NewClass'); const obj = new Parse.Object('NewClass');
obj.set('geo1', new Parse.GeoPoint({latitude: 0, longitude: 0})); obj.set('geo1', new Parse.GeoPoint({latitude: 0, longitude: 0}));
obj.save() obj.save()
.then(() => { .then(() => {
@@ -607,7 +607,7 @@ describe('schemas', () => {
}); });
it('put with no modifications returns all fields', done => { it('put with no modifications returns all fields', done => {
var obj = hasAllPODobject(); const obj = hasAllPODobject();
obj.save() obj.save()
.then(() => { .then(() => {
request.put({ request.put({
@@ -732,8 +732,8 @@ describe('schemas', () => {
}); });
it('lets you delete multiple fields and check schema', done => { it('lets you delete multiple fields and check schema', done => {
var simpleOneObject = () => { const simpleOneObject = () => {
var obj = new Parse.Object('SimpleOne'); const obj = new Parse.Object('SimpleOne');
obj.set('aNumber', 5); obj.set('aNumber', 5);
obj.set('aString', 'string'); obj.set('aString', 'string');
obj.set('aBool', true); obj.set('aBool', true);
@@ -773,7 +773,7 @@ describe('schemas', () => {
}); });
it('lets you delete multiple fields and add fields', done => { it('lets you delete multiple fields and add fields', done => {
var obj1 = hasAllPODobject(); const obj1 = hasAllPODobject();
obj1.save() obj1.save()
.then(() => { .then(() => {
request.put({ request.put({
@@ -813,9 +813,9 @@ describe('schemas', () => {
}, },
classLevelPermissions: defaultClassLevelPermissions classLevelPermissions: defaultClassLevelPermissions
}); });
var obj2 = new Parse.Object('HasAllPOD'); const obj2 = new Parse.Object('HasAllPOD');
obj2.set('aNewPointer', obj1); obj2.set('aNewPointer', obj1);
var relation = obj2.relation('aNewRelation'); const relation = obj2.relation('aNewRelation');
relation.add(obj1); relation.add(obj1);
obj2.save().then(done); //Just need to make sure saving works on the new object. obj2.save().then(done); //Just need to make sure saving works on the new object.
}); });
@@ -823,7 +823,7 @@ describe('schemas', () => {
}); });
it('will not delete any fields if the additions are invalid', done => { it('will not delete any fields if the additions are invalid', done => {
var obj = hasAllPODobject(); const obj = hasAllPODobject();
obj.save() obj.save()
.then(() => { .then(() => {
request.put({ request.put({
@@ -864,7 +864,7 @@ describe('schemas', () => {
}); });
it('refuses to delete non-empty collection', done => { it('refuses to delete non-empty collection', done => {
var obj = hasAllPODobject(); const obj = hasAllPODobject();
obj.save() obj.save()
.then(() => { .then(() => {
request.del({ request.del({
@@ -907,12 +907,12 @@ describe('schemas', () => {
}); });
it('deletes collections including join tables', done => { it('deletes collections including join tables', done => {
var obj = new Parse.Object('MyClass'); const obj = new Parse.Object('MyClass');
obj.set('data', 'data'); obj.set('data', 'data');
obj.save() obj.save()
.then(() => { .then(() => {
var obj2 = new Parse.Object('MyOtherClass'); const obj2 = new Parse.Object('MyOtherClass');
var relation = obj2.relation('aRelation'); const relation = obj2.relation('aRelation');
relation.add(obj); relation.add(obj);
return obj2.save(); return obj2.save();
}) })
@@ -1642,7 +1642,7 @@ describe('schemas', () => {
setPermissionsOnClass('AClass', { setPermissionsOnClass('AClass', {
'addField': {} 'addField': {}
}).then(() => { }).then(() => {
var obj = new Parse.Object('AClass'); const obj = new Parse.Object('AClass');
obj.set('key', 'value'); obj.set('key', 'value');
return obj.save(null, {useMasterKey: true}) return obj.save(null, {useMasterKey: true})
}).then((obj) => { }).then((obj) => {

View File

@@ -6,5 +6,6 @@
"helpers": [ "helpers": [
"../node_modules/babel-core/register.js", "../node_modules/babel-core/register.js",
"helper.js" "helper.js"
] ],
"random": false
} }

View File

@@ -4,14 +4,14 @@ import * as middlewares from '../src/middlewares';
import { ParseServer } from '../src/index'; import { ParseServer } from '../src/index';
import { Parse } from 'parse/node'; import { Parse } from 'parse/node';
var express = require('express'), const express = require('express'),
cryptoUtils = require('../src/cryptoUtils'); cryptoUtils = require('../src/cryptoUtils');
var router = express.Router(); const router = express.Router();
// creates a unique app in the cache, with a collection prefix // creates a unique app in the cache, with a collection prefix
function createApp(req, res) { function createApp(req, res) {
var appId = cryptoUtils.randomHexString(32); const appId = cryptoUtils.randomHexString(32);
ParseServer({ ParseServer({
databaseURI: 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase', databaseURI: 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase',
@@ -20,7 +20,7 @@ function createApp(req, res) {
serverURL: Parse.serverURL, serverURL: Parse.serverURL,
collectionPrefix: appId collectionPrefix: appId
}); });
var keys = { const keys = {
'application_id': appId, 'application_id': appId,
'client_key' : 'unused', 'client_key' : 'unused',
'windows_key' : 'unused', 'windows_key' : 'unused',