koa-lite/test/request/ip.js

50 lines
1.5 KiB
JavaScript
Raw Normal View History

2014-07-06 08:43:14 +00:00
'use strict';
2016-04-04 02:30:06 +00:00
const assert = require('assert');
const Stream = require('stream');
const Koa = require('../..');
const Request = require('../helpers/context').request;
2014-07-06 08:43:14 +00:00
describe('req.ip', () => {
describe('with req.ips present', () => {
it('should return req.ips[0]', () => {
2016-04-04 02:30:06 +00:00
const app = new Koa();
const req = { headers: {}, socket: new Stream.Duplex() };
app.proxy = true;
req.headers['x-forwarded-for'] = '127.0.0.1';
2014-07-06 08:43:14 +00:00
req.socket.remoteAddress = '127.0.0.2';
2016-04-04 02:30:06 +00:00
const request = Request(req, undefined, app);
request.ip.should.equal('127.0.0.1');
2015-10-12 20:36:41 +00:00
});
});
2014-07-06 08:43:14 +00:00
describe('with no req.ips present', () => {
it('should return req.socket.remoteAddress', () => {
2016-04-04 02:30:06 +00:00
const req = { socket: new Stream.Duplex() };
2014-07-06 08:43:14 +00:00
req.socket.remoteAddress = '127.0.0.2';
2016-04-04 02:30:06 +00:00
const request = Request(req);
request.ip.should.equal('127.0.0.2');
2015-10-12 20:36:41 +00:00
});
2015-10-03 01:49:20 +00:00
describe('with req.socket.remoteAddress not present', () => {
it('should return an empty string', () => {
2016-04-04 02:30:06 +00:00
const socket = new Stream.Duplex();
Object.defineProperty(socket, 'remoteAddress', {
get: () => undefined, // So that the helper doesn't override it with a reasonable value
set: () => {}
});
assert.equal(Request({ socket }).ip, '');
2015-10-12 20:36:41 +00:00
});
});
});
2016-04-04 02:30:06 +00:00
it('should be cached', () => {
const req = { socket: new Stream.Duplex() };
req.socket.remoteAddress = '127.0.0.2';
const request = Request(req);
req.socket.remoteAddress = '127.0.0.1';
request.ip.should.equal('127.0.0.2');
});
2015-10-12 20:36:41 +00:00
});