Skip to content

Commit f07a03f

Browse files
committed
test: add unit tests for selectServers method
1 parent f597e52 commit f07a03f

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
'use strict';
2+
const ReadPreference = require('../../../../lib/core/topologies/read_preference');
3+
const Topology = require('../../../../lib/core/sdam/topology');
4+
const Server = require('../../../../lib/core/sdam/server');
5+
const serverSelection = require('../../../../lib/core/sdam/server_selection');
6+
const selectServers = serverSelection.selectServers;
7+
const sc = require('../../../../lib/core/sdam/common');
8+
const expect = require('chai').expect;
9+
const sinon = require('sinon');
10+
11+
describe('selectServers', function() {
12+
beforeEach(function() {
13+
this.sinon = sinon.sandbox.create();
14+
});
15+
16+
afterEach(function() {
17+
this.sinon.restore();
18+
});
19+
20+
it('should error immediately if timeout exceeds start time', function(done) {
21+
const topology = new Topology('invalid:27019');
22+
const start = process.hrtime();
23+
start[0] = start[0] - 500;
24+
25+
selectServers(topology, ReadPreference.primary, 500, start, err => {
26+
expect(err).to.exist;
27+
done();
28+
});
29+
});
30+
31+
it('should timeout if no servers are found within `serverSelectionTimeoutMS`', function(done) {
32+
const topology = new Topology('someserver:27019');
33+
topology.s.state = sc.STATE_CONNECTED; // fake that we are already connected
34+
35+
selectServers(topology, ReadPreference.primary, 500, process.hrtime(), err => {
36+
expect(err).to.exist;
37+
expect(err).to.match(/Server selection timed out/);
38+
expect(err).to.not.have.property('reason');
39+
40+
done();
41+
});
42+
});
43+
44+
it('should schedule monitoring if no suitable server is found', function(done) {
45+
const topology = new Topology('someserver:27019');
46+
const serverMonitor = this.sinon.stub(Server.prototype, 'monitor');
47+
48+
this.sinon
49+
.stub(Topology.prototype, 'selectServer')
50+
.callsFake(function(selector, options, callback) {
51+
const server = Array.from(this.s.servers.values())[0];
52+
callback(null, server);
53+
});
54+
55+
this.sinon.stub(Server.prototype, 'connect').callsFake(function() {
56+
this.emit('connect');
57+
});
58+
59+
topology.connect(() => {
60+
selectServers(topology, ReadPreference.primary, 1000, process.hrtime(), err => {
61+
expect(err).to.exist;
62+
expect(err).to.match(/Server selection timed out/);
63+
expect(err).to.not.have.property('reason');
64+
65+
// expect a call to monitor for initial server creation, and another for the server selection
66+
expect(serverMonitor)
67+
.property('callCount')
68+
.to.equal(2);
69+
70+
topology.close(done);
71+
});
72+
});
73+
});
74+
});

0 commit comments

Comments
 (0)