Exemplo n.º 1
0
	return dag.make('d').then(function (result) {
		assert.deepEqual(result, {object: 42});
		assert.deepEqual(count, { a: 1, b: 1, c: 1, d: 1 });

		assert(when.isPromiseLike(dag.get('a')));
		assert(when.isPromiseLike(dag.get('d')));

		dag.reset();

		assert(typeof dag.get('a') === 'function');
		assert(typeof dag.get('d') === 'function');
		
	});
Exemplo n.º 2
0
 it("should return a promise", function () {
   device._seq = {
     write: function () { }
   };
   var res = device.exec("test");
   expect(when.isPromiseLike(res)).to.be.true;
 });
Exemplo n.º 3
0
    handle: function (args, shouldExit) {
        var result;

        if (!args || args.length == 2) {
            result = this.runCommand("help");
        }
        else if (args.length >= 2) {
            result = this.runCommand(args[2], args.slice(3));
        }

        if (when.isPromiseLike(result)) {
            when(result).catch(function(err) {
                if (shouldExit) {
                    process.exit(1);
                }
            });
        }
        else {
            return result;
        }
//        else {
//            if (shouldExit) {
//                process.exit(parseInt(result));
//            }
//            else {
//                return result;
//            }
//        }
    },
Exemplo n.º 4
0
    it('should make request and handle statuscode error', function (done) {
      this.object.__set__('request', mocks.request.statusCodeError(this.requestOptions, 403, {
        httpStatus: 403,
        describedBy: 'https://www.example.com/somedescription'
      }));


      var request = this.object.AkamaiRequest(this.requestOptions).then(function () {
        done(new Error('should never get here.'));
      }).catch(function (err) {
        try {
          assert.equal(typeof err.res, 'object');
          assert.equal(/Unexpected status code: 403/.test(err.toString()), true);
          assert.equal(typeof err.body, 'object');
          assert.equal(typeof err.body.describe, 'function');

          if (/Unexpected status code: 403/.test(err.toString())) {
            done();
          } else {
            done(err);
          }
        } catch (e) {
          done(e);
        }
      });

      assert.equal(when.isPromiseLike(request), true);
    });
Exemplo n.º 5
0
				return when.promise( function( resolve ) {
					if ( when.isPromiseLike( value ) ) {
						value.then( store );
					} else {
						store( value );
					}
					resolve( value );
				} );
Exemplo n.º 6
0
    it('should make request', function (done) {
      var statusRequest = this.object.AkamaiStatus('someusername', 'supersecret', this.progressUri).then(function (response) {
        assert.equal(response.httpStatus, 200);
        assert.equal(typeof response.status, 'function');
      }.bind(this)).then(done).catch(done);

      assert.equal(when.isPromiseLike(statusRequest), true);
    });
Exemplo n.º 7
0
	ObjectAdapter.canHandle = function (obj) {
		// this seems close enough to ensure that instanceof works.
		// a RegExp will pass as a valid prototype, but I am not sure
		// this is a bad thing even if it is unusual.
		// IMPORTANT: since promises *are* objects, the check for isPromise
		// must come first in the OR
		return obj && (when.isPromiseLike(obj) || Object.prototype.toString.call(obj) == '[object Object]');
	};
Exemplo n.º 8
0
function initialize( config, authProvider, fount ) {
	config = config || {};
	_.defaults( config, {
		getUserString: function( user ) {
			return user.name || user.username || user.id || JSON.stringify( user );
		}
	} );
	authProvider = authProvider || config.authProvider;
	if ( config.logging && !_.isEmpty( config.logging ) ) {
		require( './log' )( config.logging );
	}
	var metrics = require( './metrics' )( config.metrics || {} );
	var middleware = middlewareLib( sessionLib );
	var http = httpFn( request, middleware );
	var socket = socketFn( config, http );
	var state = {
		actions: undefined,
		auth: undefined,
		config: config,
		fount: fount || config.fount || internalFount,
		http: http,
		meta: undefined,
		metrics: metrics,
		middleware: middleware,
		request: request,
		resources: {},
		socket: socket,
		session: sessionLib,
		transport: undefined
	};
	var transport = state.transport = require( './transport' )( state, config );
	function onResources( x ) {
		process.nextTick( function() {
			eventChannel.publish( 'resources.loaded', x.resources );
		} );
	}
	_.merge( state, {
		on: onEvent,
		onResources: onEvent.bind( undefined, 'resources.loaded' ),
		start: transport.start,
		stop: transport.stop
	} );

	middleware.configure( config );
	if ( when.isPromiseLike( authProvider ) ) {
		authProvider
			.then( function( auth ) {
				state.auth = auth;
				setup( state, transport, auth )
					.then( onResources );
			} );
	} else {
		state.auth = authProvider;
		setup( state, transport, authProvider )
			.then( onResources );
	}
	return state;
}
Exemplo n.º 9
0
    it('should make request with bad options primitive type', function (done) {
      var purgeRequest = this.object.AkamaiPurge('someusername', 'supersecret', this.requestObjects, 'badoptions').then(function (response) {
        assert.equal(response.httpStatus, 201);
        assert.equal(typeof response.status, 'function');
        assert.deepEqual(response.requestBody, this.requestBody);
      }.bind(this)).then(done).catch(done);

      assert.equal(when.isPromiseLike(purgeRequest), true);
    });
Exemplo n.º 10
0
}).then(function (result) {
	// this second make does nothing, cause all things are built already.
	assert(when.isPromiseLike(dag.get('a')));
	assert(when.isPromiseLike(dag.get('d')));

	return dag.make('d').then(function (result) {
		assert.deepEqual(result, {object: 42});
		assert.deepEqual(count, { a: 1, b: 1, c: 1, d: 1 });

		assert(when.isPromiseLike(dag.get('a')));
		assert(when.isPromiseLike(dag.get('d')));

		dag.reset();

		assert(typeof dag.get('a') === 'function');
		assert(typeof dag.get('d') === 'function');
		
	});
}).then(function () {
Exemplo n.º 11
0
    it('should make request using object modifiers', function (done) {
      this.applyMock({type: 'cpcode', domain: 'staging'}, true);

      var purgeRequest = this.object.AkamaiPurge.staging.cpcode('someusername', 'supersecret', this.requestObjects).then(function (response) {
        assert.equal(response.httpStatus, 201);
        assert.equal(typeof response.status, 'function');
        assert.deepEqual(response.requestBody, this.requestBody);
      }.bind(this)).then(done).catch(done);

      assert.equal(when.isPromiseLike(purgeRequest), true);
    });
Exemplo n.º 12
0
    it('should make request with action option given', function (done) {
      this.applyMock({action: 'invalidate'});

      var purgeRequest = this.object.AkamaiPurge('someusername', 'supersecret', this.requestObjects, {action: 'invalidate'}).then(function (response) {
        assert.equal(response.httpStatus, 201);
        assert.equal(typeof response.status, 'function');
        assert.deepEqual(response.requestBody, this.requestBody);
      }.bind(this)).then(done).catch(done);

      assert.equal(when.isPromiseLike(purgeRequest), true);
    });
Exemplo n.º 13
0
        _.each(template, function(value, key) {

            obj[key] = _.isFunction(value) ? value.apply(scope || obj, params) : _.isPlainObject(value) ? setValues(value, params, obj) : value;

            if(when.isPromiseLike(obj[key])) {
                promises.push(obj[key]);
                obj[key].then(function(value) {
                    obj[key] = value;
                });
            }
        });
Exemplo n.º 14
0
    it('should make request', function (done) {
      this.object.__set__('request', mocks.request.goodResponse(this.requestOptions, {
        httpStatus: 200
      }));


      var request = this.object.AkamaiRequest(this.requestOptions).then(function (response) {
        assert.equal(response.httpStatus, 200);
      }.bind(this)).then(done).catch(done);

      assert.equal(when.isPromiseLike(request), true);
    });
Exemplo n.º 15
0
        _.forEach(template, function(value, key) {
            if(template.hasOwnProperty(key)) {
                obj[key] = _.isFunction(value) ? value.apply(scope || obj, params) : _.isPlainObject(value) ? setValues(value, params, obj) : value;

                if(when.isPromiseLike(obj[key])) {
                    promises.push(obj[key]);
                    obj[key].then(function(key, value) {
                        obj[key] = value;
                    }.bind(obj, key));
                }
            }
        });
Exemplo n.º 16
0
    it('should make request then make status request call', function (done) {
      var purgeRequest = this.object.AkamaiPurge('someusername', 'supersecret', this.requestObjects).then(function (response) {
        assert.equal(response.httpStatus, 201);
        assert.equal(typeof response.status, 'function');
        assert.deepEqual(response.requestBody, this.requestBody);

        return response.status();
      }.bind(this)).then(function (statusResponse) {
        assert.equal(statusResponse.httpStatus, 201);
      }).then(done).catch(done);

      assert.equal(when.isPromiseLike(purgeRequest), true);
    });
Exemplo n.º 17
0
    it('should make request with bad action option given', function (done) {
      this.applyMock({});
      this.object.__set__('console', {
        warn: function (msg) {
          assert.equal(/akamai: WARNING: Invalid purge request action\. Valid actions:/.test(msg), true);
        }
      });

      var purgeRequest = this.object.AkamaiPurge('someusername', 'supersecret', this.requestObjects, {action: 'badaction'}).then(function (response) {
        assert.equal(response.httpStatus, 201);
        assert.equal(typeof response.status, 'function');
        assert.deepEqual(response.requestBody, this.requestBody);
      }.bind(this)).then(done).catch(done);

      assert.equal(when.isPromiseLike(purgeRequest), true);
    });
Exemplo n.º 18
0
    it('should make request without progress uri then make status request call', function (done) {
      this.object.__set__('AkamaiRequest', mocks.AkamaiRequest.standardGood({
        uri: constants.AKAMAI_API_QUEUE,
        method: 'POST',
        json: this.requestBody,
        auth: {
          username: '******',
          password: '******'
        }
      }, {
        httpStatus: 201,
        detail: 'Request accepted.'
      }));

      var purgeRequest = this.object.AkamaiPurge('someusername', 'supersecret', this.requestObjects).then(function (response) {
        assert.equal(response.httpStatus, 201);
        assert.equal(typeof response.status, 'function');
        assert.deepEqual(response.requestBody, this.requestBody);

        return response.status();
      }.bind(this)).then(function () {
        throw new Error('Should have failed in the status call');
      }).catch(function (err) {
        try {
          assert.equal(err instanceof Error, true);
          if (/progressUri/.test(err.toString())) {
            assert.equal(err.toString(), 'Error: Missing progressUri from response');
            done();
          } else {
            done(err);
          }
        } catch (e) {
          done(e);
        }
      });

      assert.equal(when.isPromiseLike(purgeRequest), true);
    });
Exemplo n.º 19
0
    it('should make request and handle hard error', function (done) {
      var errToAssert = new Error('test error');
      this.object.__set__('request', mocks.request.hardError(this.requestOptions, errToAssert));


      var request = this.object.AkamaiRequest(this.requestOptions).then(function () {
        done(new Error('should never get here.'));
      }).catch(function (err) {
        try {
          assert.equal(err, errToAssert);

          if (err.toString() === 'Error: test error') {
            done();
          } else {
            done(err);
          }
        } catch (e) {
          done(e);
        }
      });

      assert.equal(when.isPromiseLike(request), true);
    });
Exemplo n.º 20
0
 const checkPromise = (promise, expected, done) => {
     expect(when.isPromiseLike(promise)).toBeTruthy();
     promise.then(function (results) {
         expect(Array.isArray(results)).toBeTruthy();
         results.forEach(function (file) {
             expect(file).toBeInstanceOf(ScanFile);
             var index = -1;
             for (var n=0; n < expected.length; n++) {
                 if (expected[n].file == file.filename) {
                     index = n;
                     expected[n].found = true;
                     break;
                 }
             }
             expect(index).toBeGreaterThan(-1);
             expect(file.domain).toEqual(expected[index].domain);
         });
         for (var n=0; n < expected.length; n++) {
             expect(expected[n].found).toBeTruthy();
         }
         done();
     });
 };
Exemplo n.º 21
0
	handle: function (args, shouldExit) {
		var result;

		if (!args || args.length === 2) {
			result = this.runCommand('help');
		} else if (args.length >= 2) {
			result = this.runCommand(args[2], args.slice(3));
		}

		if (when.isPromiseLike(result)) {
			result.done(function(res) {
				process.exit(+res || 0);
			}, function() {
				if (shouldExit) {
					process.exit(1);
				}
			});
		} else {
			if (result !== undefined) {
				process.exit(result === 0 ? 0 : 1);
				return;
			}
		}
	},
Exemplo n.º 22
0
    value: function _handlerWrapper(handlerFunc, resolved, skipOnError, service, controller, orgOutput) {
      if (!orgOutput) {
        orgOutput = { out: null, code: 200, headers: null };
      }

      // error, 40x and 50x codes
      if (orgOutput.code && orgOutput.code > 400 && skipOnError) {
        return when.resolve(orgOutput);
      }

      var deferer = when.defer();
      var resolveOutput = function resolveOutput(newOutput) {
        deferer.resolve(newOutput);
      };

      // TODO: dependency injection
      var done = function done(data, code, headers) {
        resolveOutput({
          data: data,
          code: code || orgOutput.code || 200,
          headers: headers
        });
      };
      // TODO: dependency injection
      var error = function error(data, code, headers) {
        resolveOutput({
          data: data,
          code: code || 400,
          headers: headers
        });
      };
      // TODO: dependency injection
      var fatal = function fatal(data, code, headers) {
        resolveOutput({
          data: data,
          code: code || 500,
          headers: headers
        });
      };

      // TODO: dependency injection
      var custom = function custom(data) {
        if (_.isObject(data)) {
          if (data.hasOwnProperty('filename')) {
            if (!data.header) {
              data.headers = {};
            }
            data.headers.filename = data.filename;
            delete data.filename;
          }

          resolveOutput(data);
        } else {
          service.logger.error('custom response input must be object');
        }
      };
      // ---------------------------------------

      var module = {
        '$done': ['value', done],
        '$error': ['value', error],
        '$fatal': ['value', fatal],
        '$custom': ['value', custom],
        '$output': ['value', orgOutput || {}]
      };

      // add resolved to DI
      _.forEach(resolved, function (value, key) {
        module[key] = ['value', value];
      });

      // TODO: replace this with DI lib
      try {
        var result = this._serviceManager.injectionDependency(module, service, controller.instance, handlerFunc);
      } catch (err) {
        // TODO: fix this so errors are thrown, they seem to be swallowed by DI
        error({ error: err.message });
      }

      // if function is generator then wait on yield
      if (util.isES6Function(handlerFunc)) {
        try {
          // result is generator, so co wrapper it and turn into promise
          result = co(result);
        } catch (err) {
          error({ error: err.message });
        }
      }

      // if result is promise, fire done on the result data
      if (when.isPromiseLike(result)) {
        result.then(function (output) {
          // TODO: figure out better way to handle combined input/vs just data
          // API breaking change?
          if (output && output.data && output.code) {
            done(output.data, output.code, output.headers);
          } else {
            done(output);
          }
        }).catch(function (err) {
          error({ error: err });
        });
      }
      // if result is not promise and not null or undefined
      else if (_.isObject(result) && result.data && result.code) {
          // TODO: figure out better way to handle combined input/vs just data
          // API breaking change?
          done(result.data, result.code, result.headers);
        }
        // else if result is something
        else if (result !== null && result !== undefined) {
            done(result);
          }
      // TODO: is a timer needed here in case handler never resloves the route

      return deferer.promise;
    }