Example #1
0
File: success.js Project: Azure/wns
var callback = function (error, result, done, nockFile, mockScopes) {
	try {
		assert.ifError(error);
		assert.equal(typeof result, 'object', 'Result is an object');
		assert.equal(typeof result.newAccessToken, 'string', 'New accessToken was obtained');
		assert.equal(result.statusCode, 200, 'WNS response is HTTP 200');
		assert.equal(typeof result.headers, 'object', 'HTTP response headers are present in the result');
		assert.equal(result.headers['x-wns-notificationstatus'], 'received', 'Notification was received by WNS');

		if (recordLiveSession) {
			// save recorded traffic to a file under the nock directory

			var code = [ 'exports.setupMockScopes = function (nock) { var scopes = []; var scope; '];
			while (currentRecord < nock.recorder.play().length) {
				code.push('scope = ' + nock.recorder.play()[currentRecord++]);
				code.push('scopes.push(scope);')
			};
			code.push('return scopes; };');
			fs.writeFileSync(nockFile, code.join(''));
		}						
		else
			// validate requests against all mocked endpoints have been performed
			mockScopes.forEach(function (scope) { scope.done(); });

		done();
	}
	catch (e) {
		console.log(e);
		done(e);
	}
};
var callback = function (error, result, done, nockFile, mockScopes, validation) {
	try {
		validation(error, result);

		if (recordLiveSession) {
			// save recorded traffic to a file under the nock directory

			var code = [ 'exports.setupMockScopes = function (nock) { var scopes = []; var scope; '];
			while (currentRecord < nock.recorder.play().length) {
				code.push('scope = ' + nock.recorder.play()[currentRecord++]);
				code.push('scopes.push(scope);')
			};
			code.push('return scopes; };');
			fs.writeFileSync(nockFile, code.join(''));
		}						
		else
			// validate requests against all mocked endpoints have been performed
			mockScopes.forEach(function (scope) { scope.done(); });

		done();
	}
	catch (e) {
		console.log(e);
		done(e);
	}
};
Example #3
0
export default async function getTokenAndId (email, password) {
  email = email || process.env.FACEBOOK_EMAIL
  password = password || process.env.FACEBOOK_PASSWORD

  if (!email || !password) {
    throw new Error('Define username and password via env vars')
  }

  const browser = new Browser()

  await browser.visit(FACEBOOK_AUTHENTICATION_TOKEN_URL)
  browser.fill('#email', email).fill('#pass', password)
  try {
    await browser.pressButton('#loginbutton')
  } catch (e) {
    debug('#loginbutton not found trying input[name=login]')
    await browser.pressButton("input[name='login']")
  }

  debug('passed login')
  nock.recorder.rec({output_objects: true, dont_print: true})
  try {
    await browser.pressButton("button[name='__CONFIRM__']")
  } catch (e) {
    // TODO better non critical error handling
    if (e.message === "Cannot read property 'birthdate' of null") {
      debug(`got error ${e.message} but ignoring`)
      try {
        await browser.wait()
      } catch (e) {
        nock.recorder.restore()
        nock.recorder.clear()
        throw e
      }
    } else {
      nock.recorder.restore()
      nock.recorder.clear()
      throw e
    }
  }

  var nockCallObjects = nock.recorder.play()
  let urlRegex = /\/v2\.1\/dialog\/oauth\/(confirm|read)\?dpr=[0-9]{1}/
  let tokenResponse = _.filter(nockCallObjects, (nockCallObject) => urlRegex.test(nockCallObject.path))

  nock.recorder.restore()
  nock.recorder.clear()

  if (tokenResponse.length !== 1) {
    throw new Error(`Tinderauth tokenresponse not found! length: ${tokenResponse.length}`)
  }
  debug(tokenResponse[0].response)

  let [, token] = tokenResponse[0].response.match(/#access_token=(.+)&/)
  let {data: {id: profile_id}} = await axios.get(`https://graph.facebook.com/me?access_token=${token}`)

  let ret = {token, profile_id}
  debug(ret)
  return ret
}
Example #4
0
 after: function (done) {
   if (!has_fixtures) {
     var fixtures = nock.recorder.play();
     var text = "var nock = require('nock');\n" + fixtures.join('\n');
     fs.writeFile(fp, text, done);
   } else {
     done();
   }
 }
Example #5
0
/**
 * Asserts whether some requests in the given
 * slice were made to remote entities
 */
function remoteRequests(expected) {
    const remoteReqs = nock.recorder.play().some((req) => req && !/localhost/.test(req.scope));
    deepEqual(
        remoteReqs,
        expected,
        expected ?
          'Should have made a remote request' :
          'Should not have made a remote request'
    );
}
Example #6
0
	afterEach(function() {
		var nockCalls = nock.recorder.play().filter(function(nockItem) {
			return nockItem.scope !== 'http://localhost:' + config.port;
		});
		var mockFilePath = './test/mocks/' + this.currentTest.title.replace(/\s/g, '_') + '.json';
		if (nockCalls && nockCalls.length > 0) {
			fs.writeFileSync(mockFilePath, JSON.stringify(nockCalls, null, 4));
			console.log('Nock recorded some requests and wrote to "%s"', mockFilePath);
		}
	});
function afterTest(cassettePath, options) {
  var cassettes = nock.recorder.play();

  if (cassettes.length) {
    cassettes = removeExcludedScopeFromArray(cassettes, options.excludeScope);

    return mkdirp(path.dirname(cassettePath)).then(function() {
      return writeFile(cassettePath, JSON.stringify(cassettes, null, 2));
    });
  }

  return Promise.resolve();
}
Example #8
0
 after: done => {
   if (!has_fixtures && !cheerio.browser) {
     has_fixtures = nock.recorder.play();
     // eslint-disable-next-line no-console
     console.log(
       `This is disabled for browser/node interop. To capture fixutres,
       open ${'`src/test-helpers.js`'} and uncomment lines 58 and 59 and
       the fs import at top of file.`
     );
     // const text = `const nock = require('nock');\n${has_fixtures.join('\n')}`;
     // fs.writeFile(fp, text, done);
   } else {
     done();
   }
 },
Example #9
0
    new Promise((resolve, reject) => {
      counts = {}
      const recordings = nock.recorder.play()

      // Iterate through the nock recorded HTTP requests
      console.log("Writing recordings...")
      return Promise.all(
        recordings.map(rec => {
          const host = url.parse(rec.scope).hostname
          let filename, contents

          // Determine what file to write depending on which API was requested
          if (host === GRAVITY_HOST) {
            filename = filenameFor("gravity")
            contents = zlib.gunzipSync(
              Buffer.from(rec.response.join(""), "hex")
            )
            contents = JSON.stringify(JSON.parse(contents), null, 2)
          } else if (host === METAPHYSICS_HOST) {
            filename = filenameFor("metaphysics")
            contents = JSON.stringify(rec.response, null, 2)
          } else if (host === POSITRON_HOST) {
            filename = filenameFor("positron")
            contents = JSON.stringify(rec.response, null, 2)
          }

          // Write the fixture json file
          return new Promise((resolve, reject) => {
            console.log(
              truncate(
                chalk.blue(`${last(filename.split("/"), 2).join("/")}: `) +
                  chalk.yellow(`${rec.method} ${host}${rec.path}`) +
                  (rec.body ? JSON.stringify(rec.body) : ""),
                process.stdout.columns - 3
              )
            )

            fs.writeFile(
              filename,
              contents,
              err => (err ? reject(err) : resolve())
            )
          })
        })
      ).then(() => {
        console.log("Recorded JSON responses to test/acceptance/fixtures")
      })
    }),
Example #10
0
    cleanup: function() {
      if (nockMode === 'RECORD') {
        var nockCallObjects = nock.recorder.play();
        require('fs').writeFileSync(fixtureFile, JSON.stringify(nockCallObjects, null, 2));
      }

      // makesure all internal calls were made
      try {
        for (let nockName in requiredNocks) {
          if (requiredNocks.hasOwnProperty(nockName)) {
            requiredNocks[nockName].done();
          }
        }
      }
      finally {
        nock.cleanAll();
      }
    },
Example #11
0
File: test.js Project: apis-is/apis
after(() => {
  if (process.env.RECORD_MOCK_DATA) {
    const nockCallObjects = nock.recorder.play()
    const noLocalhost = nockCallObjects.filter((o) => {
      return ![
        'http://localhost:3101',
        'http://www.m5.is:80',
        'http://hraun.vedur.is:80',
        'http://www.vedur.is:80',
        'http://www.landspitali.is:80',
        'http://fotbolti.net:80',
        'http://skoli.landsbjorg.is:80',
        'http://www.worldfengur.com:80',
      ].includes(o.scope)
    })
    fs.writeFileSync(mockDataFilename, JSON.stringify(noLocalhost, null, 2))
  }
})
Example #12
0
// after every test
function teardownFunc(done) {
    if (process.env.GCM_NOCK_REC) {
      // play nock recording
      var scope = scopeWritten ? ',\n[' : '[';
      var lineWritten;
      nock.recorder.play().forEach(function (line) {
        if (line.indexOf('nock') >= 0) {
          scope += (lineWritten ? ',\n' : '') + 'function (nock) { var result = ' + line + ' return result; }';
          lineWritten = true;
        }
      });

      if (lineWritten) {
          scope += ']';
          scopeWritten = true;
          fs.appendFileSync(__dirname + '/dpush-tests.nock.js', scope);
      }

      nock.recorder.clear();
    }

    unNockHttp();
    done();
}  
Example #13
0
function findRequests(predicate) {
    return nock.recorder.play().filter(predicate);
}
after(function () {

    //If record is truthy and we're running live, save the output.
    if (!!argv.record && !!argv.live) {

        mkdirp.sync(path.join(__dirname, "tmp"));

        let nockCallObjects = nock.recorder.play();

        for (let callObject of nockCallObjects) {
            if (callObject.scope === testSettings.valid.url + ":80") {
                callObject.scope = "http://mysharepointfarm:80";

                if (callObject.body)
                    callObject.body = "*";
            }

            //Rawheaders nonsense.
            if (callObject.rawHeaders) {
                callObject.headers = {};

                for(let i = 0; i < callObject.rawHeaders.length; i+=2) {
                    callObject.headers[callObject.rawHeaders[i].toLowerCase()] = callObject.rawHeaders[i+1];
                }
                delete callObject.rawHeaders;
            }

            if (callObject.headers) {
                for (let header in callObject.headers) {
                    let headerLower = header.toLowerCase();
                    switch (headerLower) {
                        case "expires":
                        case "last-modified":
                        case "date":
                            delete callObject.headers[header];
                            break;
                        case "x-requestdigest":
                            callObject.headers[header] = "0x12345,{{{currentDate}}}";
                            break;
                    }
                }

                //The flip-side of the rawheaders nonsense.
                callObject.rawHeaders = [];
                for (let header in callObject.headers) {
                    callObject.rawHeaders.push(header);
                    callObject.rawHeaders.push(callObject.headers[header]);
                }
                delete callObject.headers;
            }

            if (callObject.response) {
                let formDigestValue = _.get(callObject.response, "d.GetContextWebInformation.FormDigestValue");
                if (formDigestValue) {
                    _.set(callObject.response, "d.GetContextWebInformation.FormDigestValue", "0x12345,{{{currentDate}}}");
                }

                let timeCreated = _.get(callObject.response, "d.TimeCreated")
                if (timeCreated) {
                    _.set(callObject.response, "d.TimeCreated", "{{{currentDate}}}");
                }

                let timeLastModified = _.get(callObject.response, "d.TimeLastModified")
                if (timeCreated) {
                    _.set(callObject.response, "d.TimeLastModified", "{{{currentDate}}}");
                }

                let strResponse = JSON.stringify(callObject.response);
                strResponse = strResponse.replace(new RegExp(testSettings.valid.url, "g"), "{{{valid.url}}}");
                callObject.response = JSON.parse(strResponse);
            }
        }

        fs.writeFileSync(path.join(__dirname, "tmp", argv.recordOutput), JSON.stringify(nockCallObjects, null, 2));
    }
});
NockCapture.prototype.stopRecording = function() {
  this.recordedNocks = nock.recorder.play();
  this.writeNockFile();
};
var request = require("request");
var nock = require("nock");

nock.recorder.rec({
output_objects : true,
dont_print     : true
});

request.get("http://www.google.com");
request.get("http://wwww.mysite.com");
request.get("http://www.github.com");

nocks = nock.recorder.play();

nocks.forEach(function(n) {
console.log(n.scope);
console.log(n.method);
console.log(n.path);
console.log(n.status);
//console.log(n.headers);
});
Example #17
0
/**
 * Finds the first request to parsoid
 */
function findParsoidRequest() {
    return nock.recorder.play().find(function(line) {
        return line.slice && /^https?:\/\/parsoid/.test(line.scope);
    });
}
Example #18
0
 play() {
     nock.recorder.play();
 }