@function runWithAfter

merge results from run with methods into method result

@param {object} ret
@param {array} runWith

@returns {Promise}
965716
function runWithAfter (ret, runWith) {
    // after original promise resolves then run after methods
    return ret.then(res => {
        // wait for all extension methods to complete
        return Promise.all(runWith)
        // merge returned data into original
        .then(function (results) {
            // either merge or replace result
            _.each(results, result => {
                // both original res and after result are objects
                if (typeof res === 'object' && res !== null && typeof result === 'object' && result !== null) {
                    // merge after into original
                    _.merge(res, result)
                }
                // one is not an object
                else if (result !== undefined) {
                    // replace original with after
                    res = result
                }
            })
            // return final result
            return res
        })
    })
}
699207
function mapAfterAllReturn(arr, mapper, returnValue) {
  const results = new Array(arr.length);
  let containsPromise = false;

  for (let i = 0, l = arr.length; i < l; ++i) {
    results[i] = mapper(arr[i]);

    if (isPromise(results[i])) {
      containsPromise = true;
    }
  }

  if (containsPromise) {
    return Promise.all(results).then(() => returnValue);
  } else {
    return returnValue;
  }
}
1070819
function executeRelatedResultWith (result) {
    // skip if no with models specified
    if (!defined(this.args.with)) {
        return
    }
    // add related records keyed by related model name
    result._related = {}
    // load all related records
    return Promise.map(_.keys(this.args.with), relatedName => this.executeRelatedResultWithQuery(result, relatedName), {
        concurrency: this.model.concurrency,
    })
}
635808
function runNotCached (args, methodMeta) {
    // freeze args
    if (methodMeta.freeze) {
        // clone args to prevent leaking frozen objects
        args = _.cloneDeep(args)
        // recursively freeeze all objects in args
        deepFreeze(args)
    }
    // promise to be resolved with method result
    var promise
    // Immutable AI enabled
    if (methodMeta.immutableAI) {
        // create immutable ai instance
        var ai = immutableAI(args)
        // call method with Immutable AI instance
        promise = Promise.resolve( methodMeta.method.call(ai, args) )
    }
    // Immutable AI disabled
    else {
        promise = Promise.resolve( (methodMeta.method)(args) )
    }
    // args are frozen
    if (methodMeta.freeze) {
        // after result resolves clone to prevent leaking frozen objects
        promise = promise.then(_.cloneDeep)
    }
    // resolve promises
    if (methodMeta.resolve) {
        promise = promise.then(
            // if result is object then resolve promises
            ret => typeof ret === 'object' && ret !== null ? deepResolve(ret) : ret
        )
    }
    // validate return value
    if (defined(methodMeta.schema.return) && methodMeta.validateArgs) {
        promise = promise.then(ret => validateReturn(ret, methodMeta))
    }
    // return promise to be resolved with method result
    return promise
}
75512
function wrapParsePromise(promise, parsePromise) {
      ['_rejected', '_rejectedCallbacks', '_resolved', '_resolvedCallbacks', '_result', 'reject', 'resolve']
        .forEach(function (prop) {
          promise[prop] = parsePromise[prop];
        });

      ['_continueWith', '_thenRunCallbacks', 'always', 'done', 'fail'].forEach(function (method) {
        promise[method] = wrap(parsePromise[method]);
      });

      ['then', 'catch'].forEach(function (method) {
        var func = promise[method];
        promise[method] = function wrappedAngularPromise() {
          var args = Array.prototype.slice.call(arguments, 0);
          var promise = func.apply(this, args);
          wrapParsePromise(promise, parsePromise);
          return promise;
        };
      });

      return promise;
    }
110627
function onceify(f) {
  var ran, ret;
  return function() {
    return ran ? ret : (ran=true, ret=f.apply(this,arguments));
  };
}
1194043
def runQueryWithRetry(self, *args, **kw):
        

        def runQuery(txn, *args, **kw):
            txn.execute(*args, **kw)
            return txn.fetchall()

        return self.runInteractionWithRetry(runQuery, *args, **kw)
659117
def _postrun(cls, span, obj, **kwargs):
        
        for key, value in ResultSchema().dump(obj.result).items():
            if isinstance(value, dict):
                try:
                    flat_data = cls.filter_keys(
                        cls.fix_additional_fields(value)
                    )
                    span.set_tag("result.{}".format(key), json.dumps(flat_data))
                except Exception:
                    span.set_tag("result.{}".format(key), "N/A")
            elif isinstance(value, (list, tuple)):
                try:
                    span.set_tag("result.{}".format(key), json.dumps(value))
                except Exception:
                    try:
                        span.set_tag("result.{}".format(key), value)
                    except Exception:
                        span.set_tag("result.{}".format(key), "N/A")
            else:
                span.set_tag("result.{}".format(key), value)
207212
function next( ret ) {
            if( ret.done ) {
                return resolve( ret.value );
            }
            var value = toPromise.call( ctx, ret.value );
            if( value && isPromise( value ) ) {
                return value.then( onFulfilled, onRejected );
            }
            return onRejected( new TypeError( 'You may only yield a function, promise, generator, array, or object, '
                                              + 'but the following object was passed: "' + String( ret.value )
                                              + '"' ) );
        }
114355
function runSync (fn, repeatTest = 0, args = []) {
    return (resolve, reject) =>
        Fiber(() => executeSync.call(this, fn, repeatTest, args).then(() => resolve(), reject)).run()
}
804226
def after_return(self, status, retval, task_id, args, kwargs, einfo):
        
        # Only clear the lock after the task's execution if the
        # "unlock_before_run" option is False
        if not self.unlock_before_run():
            key = self.get_key(args, kwargs)
            self.once_backend.clear_lock(key)
771601
function Spec(runner, options) {
  Base.call(this, runner, options);

  var self = this;
  var indents = 0;
  var n = 0;

  function indent() {
    return Array(indents).join('  ');
  }

  runner.on(EVENT_RUN_BEGIN, function() {
    console.log();
  });

  runner.on(EVENT_SUITE_BEGIN, function(suite) {
    ++indents;
    console.log(color('suite', '%s%s'), indent(), suite.title);
  });

  runner.on(EVENT_SUITE_END, function() {
    --indents;
    if (indents === 1) {
      console.log();
    }
  });

  runner.on(EVENT_TEST_PENDING, function(test) {
    var fmt = indent() + color('pending', '  - %s');
    console.log(fmt, test.title);
  });

  runner.on(EVENT_TEST_PASS, function(test) {
    var fmt;
    if (test.speed === 'fast') {
      fmt =
        indent() +
        color('checkmark', '  ' + Base.symbols.ok) +
        color('pass', ' %s');
      console.log(fmt, test.title);
    } else {
      fmt =
        indent() +
        color('checkmark', '  ' + Base.symbols.ok) +
        color('pass', ' %s') +
        color(test.speed, ' (%dms)');
      console.log(fmt, test.title, test.duration);
    }
  });

  runner.on(EVENT_TEST_FAIL, function(test) {
    console.log(indent() + color('fail', '  %d) %s'), ++n, test.title);
  });

  runner.once(EVENT_RUN_END, self.epilogue.bind(self));
}
1112878
function future (run) {

  var result,
      resolve_listeners = [],
      reject_listeners = [],
      is_resolving = false,
      is_fullfilled = false,
      is_rejected = false,
      is_uncaught = true

  var promise = {
    then: function (onFulfilled, onRejected) {

      if( onRejected instanceof Function ) is_uncaught = false

      if( is_fullfilled && typeof onFulfilled !== 'function' ) return resolvedFuture(result)

      if( is_rejected && typeof onRejected !== 'function' ) return rejectedFuture(result)

      var _promise = future(function (_resolve, _reject) {

        var _onFulfilled = onFulfilled instanceof Function ? function (_result) {

            // nextTick( _resolveThen(_promise, onFulfilled, _result, _resolve, _reject) );

            nextTick(function () {
              try {
                _resolvePromise(_promise, onFulfilled(_result), _resolve, _reject )
              } catch(_reason) {
                _reject(_reason)
              }

              // _resolvePromise(_promise, { then: function (_complete) {
              //   if( is_completed ) return;
              //   is_completed = true;
              //   // var value = onFulfilled(_result);
              //   // if( value === promise ) console.log('TypeError promise'); // eslint-disable-line
              //   // if( value === _promise ) console.log('TypeError _promise'); // eslint-disable-line
              //   _complete( onFulfilled(_result) );
              // } }, _resolve, _reject );
            })

          } : _resolve

        var _onRejected = onRejected instanceof Function ? function (_result) {

            // nextTick( _resolveThen(_promise, onRejected, _result, _resolve, _reject) );

            nextTick(function () {
              try {
                _resolvePromise(_promise, onRejected(_result), _resolve, _reject )
              } catch(_reason) {
                _reject(_reason)
              }
              // _resolvePromise(_promise, { then: function (_complete) {
              //   if( is_completed ) return;
              //   is_completed = true;
              //   _complete( onRejected(_result) );
              // } }, _resolve, _reject );
            })

          } : _reject

        if( is_fullfilled ) _onFulfilled(result)
        else if( is_rejected ) _onRejected(result)
        else {
          resolve_listeners.push(_onFulfilled)
          reject_listeners.push(_onRejected)
        }

      })

      return _promise
    },
    catch: function (onReject) {
      return promise.then(null, onReject)
    },
  }

  var resolve = function (value) {
    if( is_resolving ) return

    is_resolving = true
    _resolvePromise(promise, value, function (_result) {

      is_fullfilled = true
      result = _result

      nextTick( _runQueue( resolve_listeners, result ) )
      reject_listeners.splice()
    }, reject)
  }

  var reject = function (reason) {
    if( is_resolving || is_fullfilled || is_rejected ) return

    is_resolving = true
    is_rejected = true
    result = reason

    nextTick( _runQueue( reject_listeners, result, is_uncaught ) )
    resolve_listeners.splice()
  }

  try{
    // run.call(promise, resolve, reject);
    run(resolve, reject)
  } catch(_reason) {
    reject(_reason)
  }

  return promise

}
900581
private <T> T executeHttpCallWithRetry(HttpCall<T> call, int runCount) {
    try {
      return call.execute();
    }
    catch (PackageManagerHttpActionException ex) {
      // retry again if configured so...
      if (runCount < props.getRetryCount()) {
        log.info("ERROR: " + ex.getMessage());
        log.debug("HTTP call failed.", ex);
        log.info("---------------");

        StringBuilder msg = new StringBuilder();
        msg.append("HTTP call failed, try again (" + (runCount + 1) + "/" + props.getRetryCount() + ")");
        if (props.getRetryDelaySec() > 0) {
          msg.append(" after " + props.getRetryDelaySec() + " second(s)");
        }
        msg.append("...");
        log.info(msg);
        if (props.getRetryDelaySec() > 0) {
          try {
            Thread.sleep(props.getRetryDelaySec() * DateUtils.MILLIS_PER_SECOND);
          }
          catch (InterruptedException ex1) {
            // ignore
          }
        }
        return executeHttpCallWithRetry(call, runCount + 1);
      }
      else {
        throw ex;
      }
    }
  }
450035
function List(runner) {
  Base.call(this, runner);

  var self = this
    , stats = this.stats
    , total = runner.total;

  runner.on('start', function(){
    console.log(JSON.stringify(['start', { total: total }]));
  });

  runner.on('pass', function(test){
    console.log(JSON.stringify(['pass', clean(test)]));
  });

  runner.on('fail', function(test, err){
    console.log(JSON.stringify(['fail', clean(test)]));
  });

  runner.on('end', function(){
    process.stdout.write(JSON.stringify(['end', self.stats]));
  });
}
1358298
function Doc(runner, options) {
  Base.call(this, runner, options);

  var indents = 2;

  function indent() {
    return Array(indents).join('  ');
  }

  runner.on(EVENT_SUITE_BEGIN, function(suite) {
    if (suite.root) {
      return;
    }
    ++indents;
    console.log('%s<section class="suite">', indent());
    ++indents;
    console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
    console.log('%s<dl>', indent());
  });

  runner.on(EVENT_SUITE_END, function(suite) {
    if (suite.root) {
      return;
    }
    console.log('%s</dl>', indent());
    --indents;
    console.log('%s</section>', indent());
    --indents;
  });

  runner.on(EVENT_TEST_PASS, function(test) {
    console.log('%s  <dt>%s</dt>', indent(), utils.escape(test.title));
    var code = utils.escape(utils.clean(test.body));
    console.log('%s  <dd><pre><code>%s</code></pre></dd>', indent(), code);
  });

  runner.on(EVENT_TEST_FAIL, function(test, err) {
    console.log(
      '%s  <dt class="error">%s</dt>',
      indent(),
      utils.escape(test.title)
    );
    var code = utils.escape(utils.clean(test.body));
    console.log(
      '%s  <dd class="error"><pre><code>%s</code></pre></dd>',
      indent(),
      code
    );
    console.log('%s  <dd class="error">%s</dd>', indent(), utils.escape(err));
  });
}
15625
function eventuallyRejectedWith(promise, expected, done) {
    all([
        promise.should.be.rejectedWith(expected)
    ], done);
}