Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic Testing for Discojs #697

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
75 changes: 72 additions & 3 deletions discojs/src/aggregator.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect } from "chai";
import { Map, Range, Set } from "immutable";

import { mock, instance } from 'ts-mockito';
import { Model, WeightsContainer } from "./index.js";
import {
Aggregator,
Expand All @@ -20,10 +20,53 @@ AGGREGATORS.forEach(([name, Aggregator]) =>
describe(`${name} implements Aggregator contract`, () => {
it("starts at round zero", () => {
const aggregator = new Aggregator();

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's not needed (and is being shown as very red in my git diff).

we don't enforce a formatter yet but I'm all for slowly moving to prettier (that is, when you add changes, prettify it around, but not the whole file if you only changed a line). I'm hopeful that the transition will be smoother this way.

expect(aggregator.round).to.equal(0);
});

it("starts with no contributions", () => {
const aggregator = new Aggregator();

expect(aggregator.size).to.equal(0);
})

it("model correctly initialized", () => {
const aggregator = new Aggregator();

const model = mock(Model);

aggregator.setModel(instance(model));
expect(aggregator.model).to.equal(instance(model));
});

it("is full when created with no nodes", () => {
const aggregator = new Aggregator();

expect(aggregator.isFull());
});

it("is not full when created with more than no nodes and empty", () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
it("is not full when created with more than no nodes and empty", () => {
it("is empty when without contributions", () => {

const aggregator = new Aggregator();
aggregator.setNodes(Set.of("client 0"));

expect(aggregator.isFull()).to.be.false;
});


Comment on lines +54 to +55
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too much whitespaces

Suggested change


it("is full when enough contributions", () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
it("is full when enough contributions", () => {
it("is full with enough contributions", () => {

const aggregator = new Aggregator();
aggregator.setNodes(Set.of("client 0", "client 1", "client 2"));

for (let i = 0; i < 3; i++)
for (let r = 0; r < aggregator.communicationRounds; r++)
aggregator.add(`client ${i}`, WeightsContainer.of([i]), 0, r);

expect(aggregator.isFull()).to.be.true;
});


Comment on lines +67 to +68
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whitespaces

Suggested change


it("moves forward with enough contributions", async () => {
const aggregator = new Aggregator();
aggregator.setNodes(Set.of("client 0", "client 1", "client 2"));
Expand All @@ -35,10 +78,36 @@ AGGREGATORS.forEach(([name, Aggregator]) =>
aggregator.add(`client ${i}`, WeightsContainer.of([i]), 0, r);

await results; // nothing to test

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ws

expect(aggregator.round).to.equal(1);
});

it("does not move forward with not enough contributions", async () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

double negation are hard on my brain. it also feels as a duplicate of the previous one. you can merge the two and check that it didn't advance with only two clients contributions but does with three.

const aggregator = new Aggregator();
aggregator.setNodes(Set.of("client 0", "client 1", "client 2"));

const results = aggregator.receiveResult();

for (let i = 0; i < 2; i++)
for (let r = 0; r < aggregator.communicationRounds; r++)
aggregator.add(`client ${i}`, WeightsContainer.of([i]), 0, r);

await results;

expect(aggregator.round).to.equal(0);
});

it("Adding at the wrong round does not count", () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reads more nicely. also, you can keep the test itself smaller by not having three clients but only one. less code == faster to understand => less bug.

Suggested change
it("Adding at the wrong round does not count", () => {
it("drops contributions for futur rounds", () => {

const aggregator = new Aggregator();
aggregator.setNodes(Set.of("client 0", "client 1", "client 2"));

for (let i = 0; i < 3; i++)
for (let r = 0; r < aggregator.communicationRounds; r++)
aggregator.add(`client ${i}`, WeightsContainer.of([i]), aggregator.round+1, r);

expect(aggregator.size).to.equal(0);
});

it("gives same results on each node", async () => {
const network = setupNetwork(Aggregator);

Expand Down
6 changes: 6 additions & 0 deletions discojs/src/client/federated/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ export class Base extends Client {
const received = await waitMessageWithTimeout(
this.server,
type.AssignNodeID,
undefined,
"Timeout waiting for own id"
);
console.info(`[${received.id}] assign id generated by the server`);
this._ownId = received.id;
Expand Down Expand Up @@ -121,6 +123,8 @@ export class Base extends Client {
const { payload, round } = await waitMessageWithTimeout(
this.server,
type.ReceiveServerPayload,
undefined,
"Timeout waiting for server payload"
);
const serverRound = round;

Expand Down Expand Up @@ -162,6 +166,8 @@ export class Base extends Client {
const received = await waitMessageWithTimeout(
this.server,
type.ReceiveServerMetadata,
undefined,
"Timeout waiting for metadata map",
);
if (received.metadataMap !== undefined) {
this.metadataMap = Map(
Expand Down
53 changes: 44 additions & 9 deletions discojs/src/weights/aggregation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,68 @@ import { WeightsContainer, aggregation } from './index.js'

describe('weights aggregation', () => {
it('avg of weights with two operands', () => {
const actual = aggregation.avg([
const expected = aggregation.avg([
WeightsContainer.of([1, 2, 3, -1], [-5, 6]),
WeightsContainer.of([2, 3, 7, 1], [-10, 5]),
WeightsContainer.of([3, 1, 5, 3], [-15, 19])
])
const expected = WeightsContainer.of([2, 2, 5, 1], [-10, 10])
const actual = WeightsContainer.of([2, 2, 5, 1], [-10, 10])

assert.isTrue(actual.equals(expected))
assert.isTrue(expected.equals(actual))
})

it('sum of weights with two operands', () => {
const actual = aggregation.sum([
const expected = aggregation.sum([
[[3, -4], [9]],
[[2, 13], [0]]
])
const expected = WeightsContainer.of([5, 9], [9])
const actual = WeightsContainer.of([5, 9], [9])

assert.isTrue(actual.equals(expected))
assert.isTrue(expected.equals(actual))
})

it('diff of weights with two operands', () => {
const actual = aggregation.diff([
const expected = aggregation.diff([
[[3, -4, 5], [9, 1]],
[[2, 13, 4], [0, 1]]
])
const expected = WeightsContainer.of([1, -17, 1], [9, 0])
const actual = WeightsContainer.of([1, -17, 1], [9, 0])

assert.isTrue(actual.equals(expected))
assert.isTrue(expected.equals(actual))
})

it('avg of weights with no operands throws an error', () => {
assert.throws(() => aggregation.avg([]))
})

it('sum of weights with no operands throws an error', () => {
assert.throws(() => aggregation.sum([]))
})

it('diff of weights with no operands throws an error', () => {
assert.throws(() => aggregation.diff([]))
})

it('avg of weights with different dimensions throws an error', () => {
assert.throws(() => aggregation.avg([
[[3, -4], [9]],
[[2, 13, 4], [0, 1]]
]))
})

it('sum of weights with different dimensions throws an error', () => {
assert.throws(() => aggregation.sum([
[[3, -4], [9]],
[[2, 13, 4], [0, 1]]
]))
})

it('diff of weights with different dimensions throws an error', () => {
assert.throws(() => aggregation.diff([
[[3, -4], [9]],
[[2, 13, 4], [0, 1]]
]))
})
Comment on lines +37 to +68
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a bench test, you can simplify it by using a Set(…).forEach((op) => …)

while at it, should it fail? an addition without value can be zero, a multiplication can be one; why is this test needed?

Suggested change
it('avg of weights with no operands throws an error', () => {
assert.throws(() => aggregation.avg([]))
})
it('sum of weights with no operands throws an error', () => {
assert.throws(() => aggregation.sum([]))
})
it('diff of weights with no operands throws an error', () => {
assert.throws(() => aggregation.diff([]))
})
it('avg of weights with different dimensions throws an error', () => {
assert.throws(() => aggregation.avg([
[[3, -4], [9]],
[[2, 13, 4], [0, 1]]
]))
})
it('sum of weights with different dimensions throws an error', () => {
assert.throws(() => aggregation.sum([
[[3, -4], [9]],
[[2, 13, 4], [0, 1]]
]))
})
it('diff of weights with different dimensions throws an error', () => {
assert.throws(() => aggregation.diff([
[[3, -4], [9]],
[[2, 13, 4], [0, 1]]
]))
})
Set.of(aggregation.avg, aggregation.sum, aggregation.diff).forEach((op) => {
it(`${op.name} of weights with no operands throws`, () =>
expect(() => op([])).to.throw());
it(`${op.name} of weights with different dimensions throws`, () =>
expect(() => op([[[1, 2]], [[3, 4, 5]]])).to.throw());
});



})
12 changes: 11 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"webapp"
],
"dependencies": {
"immutable": "4"
"immutable": "4",
"ts-mockito": "^2.6.1"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the root package.json is hardly ever changed, especially for dev deps used in a single package. I use it for syncing version of dependencies that are needed across many packages.
please modify discojs/package.json if you want to add a package for discojs. (which you probably don't need as stated previously)

},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "7",
Expand Down
39 changes: 31 additions & 8 deletions server/src/router/decentralized/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,37 @@
public isValidUrl (url: string | undefined): boolean {
const splittedUrl = url?.split('/')

return (
splittedUrl !== undefined &&
splittedUrl.length === 3 &&
splittedUrl[0] === '' &&
this.isValidTask(splittedUrl[1]) &&
this.isValidWebSocket(splittedUrl[2])
)
}
// Assuming this code is inside a method of a class
console.log("Evaluating URL validation...");

if (splittedUrl === undefined) {
console.log("Failure: URL is undefined.");
return false;
}

if (splittedUrl.length !== 3) {
console.log(`Failure: URL does not have exactly 3 segments. Found ${splittedUrl.length} segments: ${splittedUrl}`);

Check failure on line 43 in server/src/router/decentralized/server.ts

View workflow job for this annotation

GitHub Actions / lint-server

Invalid type "string[]" of template literal expression
return false;
}

if (splittedUrl[0] !== '') {
console.log("Failure: URL does not start with a '/'.");
return false;
}

if (!this.isValidTask(splittedUrl[1])) {
console.log(`Failure: '${splittedUrl[1]}' is not a valid task.`);
return false;
}

if (!this.isValidWebSocket(splittedUrl[2])) {
console.log(`Failure: '${splittedUrl[2]}' is not a valid WebSocket.`);
return false;
}

console.log("URL is valid.");
return true;
}

protected initTask (): void {}

Expand Down
4 changes: 3 additions & 1 deletion server/src/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,17 @@ export class Router {
const decentralized = new Decentralized(wsApplier, this.tasksAndModels)

this.ownRouter = express.Router()
wsApplier.applyTo(this.ownRouter)
wsApplier.applyTo(this.ownRouter)

process.nextTick(() =>
wsApplier.getWss().on('connection', (ws, req) => {
if (!federated.isValidUrl(req.url) && !decentralized.isValidUrl(req.url)) {
console.log('Connection refused')
ws.send('404')
ws.terminate()
ws.close()
}
ws.send('200')
})
)

Expand Down
Loading
Loading