beforeEach(function() { objects = []; agent = superagent.agent(); objects.push({"id":11079,"message":"Uncomfortably admires","toPhoneNumber":"Snide extracurricular"}); objects.push({"id":71013,"message":"Canoes Luxembourgers","toPhoneNumber":"Breather bacteriological"}); objects.push({"id":73673,"message":"Mysteriousness authoritatively","toPhoneNumber":"Boole immaculately"}); objects.push({"id":23426,"message":"Souping pallbearers","toPhoneNumber":"Accrediting medical"}); objects.push({"id":33991,"message":"Imperilled understatement","toPhoneNumber":"Thackeray altruistic"}); objects.push({"id":85801,"message":"Tabby theirs","toPhoneNumber":"Countdown queerer"}); objects.push({"id":5888,"message":"Exterminators decriminalized","toPhoneNumber":"Rafael around"}); objects.push({"id":9277,"message":"Mystically ambidextrously","toPhoneNumber":"Balling filibustering"}); objects.push({"id":87431,"message":"Woodcarving mystification","toPhoneNumber":"Centenaries Dumbo"}); objects.push({"id":11982,"message":"Volleyballs disconnections","toPhoneNumber":"Dryness Iceland"}); V1Twilio.request = function(a, url, vals, context, cb) { cb(null, objects); }; });
constructor(ctx: HullContextObject) { const { ship, client, metric } = ctx; this.apiKey = _.get(ship, "private_settings.api_key"); this.domain = _.get(ship, "private_settings.domain"); this.listId = _.get(ship, "private_settings.mailchimp_list_id"); this.client = client; // if (_.isEmpty(this.domain) || _.isEmpty(this.apiKey) || _.isEmpty(this.listId)) { // throw new Error("Mailchimp access data not set!"); // } this.agent = superagent .agent() .use(superagentErrorPlugin()) .use( superagentUrlTemplatePlugin({ listId: this.listId }) ) .use( superagentInstrumentationPlugin({ logger: this.client.logger, metric }) ) .use(prefixPlugin(`https://${this.domain}.api.mailchimp.com/3.0`)) .set({ Authorization: `OAuth ${this.apiKey}` }) .ok(res => res.status < 500 && res.status !== 429) // we reject the promise for 5xx and 429 status codes .timeout({ response: 50000 }) .retry(2); }
app.get('/query', function (req, res) { var agent = superagent.agent(); var formData = { xh: req.query.xh, xb: req.query.xb, xm: req.query.xm, }; formData = urlencode.stringify(formData, {charset: 'gbk'}); if (queryCache[formData]) { return res.send(queryCache[formData]); } var ep = new eventproxy(); agent .post('http://pead.scu.edu.cn/jncx/logins.asp') .send(formData) .parse(superagentparse('gbk')) .end(function (err, result) { ep.emitLater('login'); }); ep.on('login', function () { agent .get('http://pead.scu.edu.cn/jncx/tcsh2.asp') .parse(superagentparse('gbk')) .end(function (err, result) { var $ = cheerio.load(result.text); res.type('html'); var body = $('body').html() || '参数有错或无数据'; queryCache[formData] = body; res.send(body); }); }); });
OAuthImpl.prototype.verifyApiKey = function(apiKey, request, cb) { var r = { apiKey: apiKey }; debug('verifyApiKey request: %j', r); var self = this; if (self.hasApigeeAccess) { self.apigee.verifyApiKey(undefined, r, function(err, data) { if (err) { cb(err); } else { checkResultError(data, function(err, result) { cb(err, result); }); } }); } else { superagent.agent(). post(self.uri + '/v2/oauth/verifyApiKey'). set('x-DNA-Api-Key', self.key). type('json'). send(r). end(function(err, resp) { if (err) { cb(err); } else { debug('Verify response: %j', resp.body); checkResultError(resp.body, function(err, result) { cb(err, result); }); } }); } };
function createCredentials(self, request, options, cb) { if (self.hasApigeeAccess) { debug('Local generateAccessToken %s', request.grantType); self.apigee.generateAccessToken(request, function(err, result) { if (err) { cb(err); } else { checkResultError(result, cb); } }); } else { debug('Remote generateAccessToken %j', request); superagent.agent(). post(self.uri + '/v2/oauth/generateAccessToken'). set('x-DNA-Api-Key', self.key). type('json'). send(request). end(function(err, resp) { if (err) { debug('createCredentials error: %s', err); cb(err); } else { debug('Create credentials response: %j', resp.body); checkResultError(resp.body, cb); } }); } }
Topic.create(topics, function(error, topics) { assert.ifError(error); var now = new Date(); // five minutes ago var date = new Date(now.getTime() - 5*60*1000); var url = URL_ROOT + '/list/abcxyz/' + date.getTime(); // Make an HTTP request to localhost:3000/topic/list/abcxyz/:date var agent = superagent.agent(); agent.get(url) .set('Authorization', 'Bearer suMwoiihHZkYuYq') .end(function(error, res) { assert.ifError(error); var result; assert.doesNotThrow(function() { result = JSON.parse(res.text); }); assert.ok(result); assert.equal(result.length, 2); assert.equal(result[0].title, 'Alpha-Beta is for Google'); assert.equal(result[0].category, 'abcxyz'); assert.equal(result[1].title, 'Apple mackook'); assert.equal(result[0].category, 'abcxyz'); done(); }); });
describe('Succesfully updates a customer', function() { var agent = request.agent(); it('should Succesfully updates a customer', function(done) { var path = require('path'); var body = require(path.resolve('services/customers/customer','putCustomer-requestBody.json')); agent .put('http://localhost:3007/rest/customers/1') .auth('username', 'password') .send(body) .set('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') .set('Accept-Encoding', 'gzip, deflate') .end(function(err, res) { should.not.exist(err); res.should.have.status(200); res.should.have.header('Content-Type', 'application/json'); res.should.have.property('body'); // FIXME add further checks if appropriate done(); }); }); });
it('should log in a user when token is valid', function(done) { var agent = superagent.agent(); // generate random key for test user and save to db var key = 'acbd1234'; adapter.find('name', 'tf', function(err, user) { user.twoFactorKey = key; adapter.update(user, function(err, user) { // login agent .post(config.url + '/login') .send({login: '******', password: '******'}) .end(function(err, res) { res.text.should.containEql('Two-Factor Authentication'); agent.saveCookies(res); var token = totp.gen(key, {}); // use two-factor authentication agent .post(config.url + '/login/two-factor') .send({token: token}) .end(function(err, res) { res.redirects.should.eql(['http://localhost:3000/']); // now access private page agent .get(config.url + '/test') .end(function(err, res) { res.statusCode.should.equal(200); res.text.should.containEql('well done'); done(); }); }); }); }); }); });
it(data.name + ' #FPT', function(done){ var agent = superagent.agent(); var id; var method; switch(data.method){ case 'DELETE': method = 'del'; break; default: method = data.method.toLowerCase(); } var simpleServer = server({port : fhPORT, protocol : data.protocol}, {}, function() { var req = agent [method](RUSHENDPOINT + data.path ) .set('x-relayer-host', ENDPOINT) //Always the same endpoint .set('x-relayer-persistence','BODY') .set('content-type','application/json') .set(data.headers); if(data.method === 'POST' || data.method === 'PUT'){ req = req.send(data.body); } req.end(function(err, res) { expect(err).to.not.exist; expect(res.statusCode).to.eql(CREATED); expect(res.body).to.exist; expect(res.body.id).to.exist; id=res.body.id; res.text.should.not.include('exception'); // done(); }); }, function(dataReceived) { expect(dataReceived).to.exist; dataReceived.method.should.be.equal(data.method); dataReceived.url.should.be.equal(data.path); var checked = false; setTimeout(function() { agent .get(RUSHENDPOINT +'/response/' + id) .end(function onResponse2(err, res) { expect(err).to.not.exist; expect(res).to.exist; expect(res.statusCode).to.equal(200); expect(res.body).to.exist; expect(res.body['body']).to.equal('Request Accepted'); res.headers['content-type'].should.eql('application/json; charset=utf-8'); res.text.should.include('id'); res.text.should.include('state'); done(); }); }, TIMEOUT); }); serversToShutDown.push(simpleServer); });
describe('Successfully delete the customer', function() { var agent = request.agent(); it('should Successfully delete the customer', function(done) { agent .del('http://localhost:3007/rest/customers/1') .auth('username', 'password') .set('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') .set('Accept-Encoding', 'gzip, deflate') .end(function(err, res) { should.not.exist(err); res.should.have.status(200); res.should.have.header('Content-Type', 'application/json'); res.should.have.property('body'); // FIXME add further checks if appropriate done(); }); }); });
after(function( done ){ var agent = superagent.agent(); // agent.del('http://localhost:1337/socrata/tester') // .end( function( err, res ) { done(); // }); });
describe('User', function () { var agent1 = request.agent(); // it('should receive forbidden from posts API', function () { // agent1.get('http://*****:*****@example.com', password: '******' }) .end(function (err, res) { should.not.exist(err); res.should.have.status(200); }); }); });
exports.requestWithHeaders = function( api, params, format, headers, callback ) { var f = 'json'; if( (typeof format ) == 'function' ) { // Use default format 'json' callback = format; } else { f = ( format === 'xml' ? 'xml' : 'json' ); } // Attach the specified headers. var _headers = {}; for( var k in HEADERS ) { _headers[k] = headers[k] ? headers[k] : HEADERS[k]; } superagent.agent() .post( BASEURL + api + '.' + f ) .set( _headers ) .send( params ) .end( function( err, result ) { if( err ) { return callback( err, result ? result.text : null ); } else { return callback( null, result.text ); } } ); }
exports.requestWithSameFields = function( api, params, fieldAndValues, format, callback ) { var f = 'json'; if( (typeof format ) == 'function' ) { // Use default format 'json' callback = format; } else { f = ( format === 'xml' ? 'xml' : 'json' ); } var agent = superagent.agent() .post( BASEURL + api + '.' + f ) .set( HEADERS ); for( var i=0; i<fieldAndValues.length; ++i ) { var field = fieldAndValues[i].field; var values = fieldAndValues[i].values; for( var j=0; j<values.length; ++j ) { agent = agent.send( field + '=' + values[j] ); } } for( var k in params ) { agent = agent.send( k + '=' + params[k] ); } agent.end( function( err, result ) { if( err ) { return callback( err, result ? result.text : null ); } else { return callback( null, result.text ); } } ); }
exports.httpGet = function(opts, req) { var env = req.query.env ? req.query.env : "production"; var url = URLS[env]; opts.url = url + opts.path; if (req.query.site) opts.query.siteId = siteEnum[req.query.site]; var deferred = Q.defer(); var agent = superagent.agent(); // console.log(req.ip); // console.log(opts); agent.get(opts.url) .query(opts.query) .end(function(res) { if (res.ok) { deferred.resolve(res); } else { deferred.reject(res.text); } }); return deferred.promise; };
ApigeeOldRemoteQuota.prototype.apply = function(opts, cb) { var allow = opts.allow || this.quota.options.allow; var r = { identifier: opts.identifier, weight: opts.weight, interval: this.quota.options.interval, allow: allow, unit: this.quota.options.timeUnit }; debug('Old remote quota request: %j', r); superagent.agent(). post(this.quota.options.uri + '/quotas/distributed'). set('x-DNA-Api-Key', this.quota.options.key). type('form'). send(r). end(function(err, resp) { if (err) { cb(err); } else if (resp.ok) { debug('result: %s', resp.text); var result = { allowed: resp.body.allowed, used: resp.body.used, isAllowed: !resp.body.failed, expiryTime: resp.body.expiry_time - resp.body.ts }; cb(undefined, result); } else { cb(new Error(util.format('Error updating remote quota: %d %s', resp.statusCode, resp.text))); } }); };
function Spotify () { if (!(this instanceof Spotify)) return new Spotify(); EventEmitter.call(this); this.seq = 0; this.heartbeatInterval = 18E4; // 180s, from "spotify.web.client.js" this.agent = superagent.agent(); this.connected = false; // true after the WebSocket "connect" message is sent this._callbacks = Object.create(null); this.authServer = 'play.spotify.com'; this.authUrl = '/xhr/json/auth.php'; this.landingUrl = '/'; this.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.46 Safari/537.36'; // base URLs for Image files like album artwork, artist prfiles, etc. // these values taken from "spotify.web.client.js" this.sourceUrl = 'https://d3rt1990lpmkn.cloudfront.net'; this.sourceUrls = { tiny: this.sourceUrl + '/60/', small: this.sourceUrl + '/120/', normal: this.sourceUrl + '/300/', large: this.sourceUrl + '/640/', avatar: this.sourceUrl + '/artist_image/' }; // mappings for the protobuf `enum Size` this.sourceUrls.DEFAULT = this.sourceUrls.normal; this.sourceUrls.SMALL = this.sourceUrls.tiny; this.sourceUrls.LARGE = this.sourceUrls.large; this.sourceUrls.XLARGE = this.sourceUrls.avatar; this.sourceUrls[0] = this.sourceUrls.DEFAULT; this.sourceUrls[1] = this.sourceUrls.SMALL; this.sourceUrls[2] = this.sourceUrls.LARGE; this.sourceUrls[3] = this.sourceUrls.XLARGE; // WebSocket agent this.wsAgent = new https.Agent(); this.wsAgent.createConnection = createHttpsConnection; // WebSocket callbacks this._onopen = this._onopen.bind(this); this._onclose = this._onclose.bind(this); this._onmessage = this._onmessage.bind(this); // start the "heartbeat" once the WebSocket connection is established this.once('connect', this._startHeartbeat); // handle "message" commands... this.on('message', this._onmessagecommand); // needs to emulate Spotify's "CodeValidator" object this._context = vm.createContext(); this._context.reply = this._reply.bind(this); // binded callback for when user doesn't pass a callback function this._defaultCallback = this._defaultCallback.bind(this); }
function Spotify () { if (!(this instanceof Spotify)) return new Spotify(); EventEmitter.call(this); this.seq = 0; this.heartbeatInterval = 18E4; // 180s, from "spotify.web.client.js" this.agent = superagent.agent(); this.connected = false; // true after the WebSocket "connect" message is sent this._callbacks = Object.create(null); this.authServer = 'play.spotify.com'; this.authUrl = '/xhr/json/auth.php'; this.secretUrl = '/redirect/facebook/notification.php'; this.userAgent = 'node-spotify-web (Chrome/13.37 compatible-ish)'; // the query-string to send along to the "secret url" this.secretPayload = { album: 'http://open.spotify.com/album/2mCuMNdJkoyiXFhsQCLLqw', song: 'http://open.spotify.com/track/6JEK0CvvjDjjMUBFoXShNZ' }; // the client version to "emulate" this.clientVersion = 41800000; // client version: 0.4.18.0, deployed 2013-05-17 13:15 UTC // base URLs for Image files like album artwork, artist prfiles, etc. // these values taken from "spotify.web.client.js" this.sourceUrl = 'https://d3rt1990lpmkn.cloudfront.net'; this.sourceUrls = { tiny: this.sourceUrl + '/60/', small: this.sourceUrl + '/120/', normal: this.sourceUrl + '/300/', large: this.sourceUrl + '/640/', avatar: this.sourceUrl + '/artist_image/' }; // mappings for the protobuf `enum Size` this.sourceUrls.DEFAULT = this.sourceUrls.normal; this.sourceUrls.SMALL = this.sourceUrls.tiny; this.sourceUrls.LARGE = this.sourceUrls.large; this.sourceUrls.XLARGE = this.sourceUrls.avatar; // WebSocket callbacks this._onopen = this._onopen.bind(this); this._onclose = this._onclose.bind(this); this._onmessage = this._onmessage.bind(this); // start the "heartbeat" once the WebSocket connection is established this.once('connect', this._startHeartbeat); // handle "message" commands... this.on('message', this._onmessagecommand); // needs to emulate Spotify's "CodeValidator" object this._context = vm.createContext(); this._context.reply = this._reply.bind(this); // binded callback for when user doesn't pass a callback function this._defaultCallback = this._defaultCallback.bind(this); }
.then(function (res) { var loginAgent = superagent.agent(); loginAgent.saveCookies(res); if (agentCallback) { agentCallback(loginAgent); } done(); }).catch(function (err) {
it('index', function(done){ superagent.agent() .get(helper.url+'/butter') .end( function(err,res){ expect(res.status).to.eql(200); expect(res.body).to.be.instanceOf(Array); done(); }); });
it('should render an error message', function (done) { request.agent() .get(urls.edit + '?resetToken=abc+123') .end(function (err, res) { res.text.should.include('<title>Password Reset</title>') res.text.should.include('Your reset token is invalid.'); done(); }); });
it('should render an error message', function (done) { request.agent() .post(urls.update) .send({}) .end(function (err, res) { res.text.should.include('Your reset token is invalid.'); done(); }); });
newUser.save(function(err, user) { userAgent = agent.agent(); userAgent .post('localhost:' + server.get('port') + '/v1/session') .send({ username: '******', password: '******' }) .end(function(err, res) { done() }); })
describe('Sequence', function() { var agent = request.agent(); var savedId = ''; it('should login', function(done) { agent.post(config.SERVER_ADDRESS + '/login').send(testUser).end(function(err, res) { should.not.exist(err); res.should.have.status(200); done(); }); }); it('should post', function(done) { agent.post(config.SERVER_ADDRESS + '/exercise').send({ name: 'abc', standardIncrease: 2.5, sync: 123 }).end(function(err, res) { should.not.exist(err); res.should.have.status(200); var json = JSON.parse(res.text); json.should.have.property('name', 'abc'); json.should.have.property('standardIncrease', 2.5); json.should.have.property('sync', 123); json.should.have.keys('_id', 'name', 'standardIncrease', 'sync'); savedId = json._id; done(); }); }); it('should del', function(done) { agent.del(config.SERVER_ADDRESS + '/exercise/' + savedId).end(function(err, res) { should.not.exist(err); res.should.have.status(200); var json = JSON.parse(res.text); json.should.have.property('_id', savedId); json.should.have.keys('_id'); done(); }); }); it('should get', function(done) { // After one add and remove agent.get(config.SERVER_ADDRESS + '/sync').end(function(err, res) { should.not.exist(err); res.should.have.status(200); var json = JSON.parse(res.text); json.should.have.length(1); var o = json[0]; o.should.have.property('table', 'exercise'); o.should.have.property('hash', 0); o.should.have.property('counter', 1); o.should.have.keys('table', 'hash', 'counter'); done(); }); }); });
function Ello(){ if(!(this instanceof Ello)) return new Ello(); EventEmitter.call(this); this.agent = superagent.agent(); this.siteLocation = 'https://ello.co/'; this.apiLocation = this.siteLocation + 'api/v1/'; }
user.save(function(){ agent = request.agent() agent.post(helpers.apiRoot+"users/login/") .send({id:user.id}) .end(function(err,res){ if (err) return done(err) setTimeout(done,0) //agent saves cookie asynchroniously }) })
it('should render a resetToken field with the query value', function (done) { request.agent() .get(urls.edit + '?resetToken=abc_-123') .redirects(0) .end(function (err, res) { res.text.should.include('<input type="hidden" name="user[resetToken]" value="abc_-123">') done(); }); });
it('gets database errors from invalid queries - amount: gh(500)', function(done){ var test = this; superagent.agent() .get(helper.url+'/butter/find?amount=gh(500)') .end( function(err,res){ expect(res.status).to.eql(500); done(); }); });
it('should display an error message', function (done) { request.agent() .post(urls.create) .send({}) .end(function (err, res) { res.text.should.include('Please enter a valid email address.'); done(); }); });
agent.get('http://localhost:8102/404.html').end(function(err, rsp){ rsp.should.have.status(200) rsp.text.should.eql(contents.toString()) var agent = superagent.agent() agent.get('http://localhost:8102/missing/path').end(function(err, rsp){ rsp.should.have.status(404) rsp.text.should.eql(contents.toString()) done() }) })