koa-lite/test/request/ip.js

60 lines
1.9 KiB
JavaScript
Raw Permalink 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);
2017-05-11 03:30:32 +00:00
assert.equal(request.ip, '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);
2017-05-11 03:30:32 +00:00
assert.equal(request.ip, '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 lazy inited and cached', () => {
2016-04-04 02:30:06 +00:00
const req = { socket: new Stream.Duplex() };
req.socket.remoteAddress = '127.0.0.2';
const request = Request(req);
assert.equal(request.ip, '127.0.0.2');
2016-04-04 02:30:06 +00:00
req.socket.remoteAddress = '127.0.0.1';
2017-05-11 03:30:32 +00:00
assert.equal(request.ip, '127.0.0.2');
2016-04-04 02:30:06 +00:00
});
it('should reset ip work', () => {
const req = { socket: new Stream.Duplex() };
req.socket.remoteAddress = '127.0.0.2';
const request = Request(req);
assert.equal(request.ip, '127.0.0.2');
request.ip = '127.0.0.1';
assert.equal(request.ip, '127.0.0.1');
});
2015-10-12 20:36:41 +00:00
});