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

Poll model - page /relations results #3073

Merged
merged 42 commits into from
Feb 1, 2023
Merged
Show file tree
Hide file tree
Changes from 39 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
5ca533c
first cut poll model
Dec 30, 2022
984e5eb
process incoming poll relations
Dec 30, 2022
e578d84
allow alt event types in relations model
Jan 4, 2023
1123f1d
allow alt event types in relations model
Jan 4, 2023
ea71efe
remove unneccesary checks on remove relation
Jan 4, 2023
dfe4038
comment
Jan 4, 2023
515db7a
Revert "allow alt event types in relations model"
Jan 4, 2023
ae6ffb7
Revert "Revert "allow alt event types in relations model""
Jan 4, 2023
f189901
Merge branch 'psg-1014/relations-alt-event-types' into psg-1014/poll-…
Jan 4, 2023
cace5d4
basic handling for new poll relations
Jan 4, 2023
6b4f630
Merge branch 'develop' into psg-1014/poll-model
Jan 5, 2023
0f7829a
tests
Jan 9, 2023
32abfed
test room.processPollEvents
Jan 9, 2023
797123c
join processBeaconEvents and poll events in client
Jan 9, 2023
51896e1
Merge branch 'develop' into psg-1014/poll-model
Jan 9, 2023
ad49a00
Merge branch 'develop' into psg-1014/poll-model
Jan 10, 2023
b158dcc
tidy and set 23 copyrights
Jan 11, 2023
924a6c0
use rooms instance of matrixClient
Jan 11, 2023
d09700f
tidy
Jan 11, 2023
9e0d95e
more copyright
Jan 11, 2023
b173130
simplify processPollEvent code
Jan 12, 2023
15dd1c4
Merge branch 'develop' into psg-1014/poll-model
Jan 12, 2023
4a0494c
throw when poll start event has no roomId
Jan 12, 2023
07d154a
Merge branch 'develop' into psg-1014/poll-model
Jan 15, 2023
68ffea1
updates for events-sdk move
Jan 16, 2023
7d8f51c
more type changes for events-sdk changes
Jan 16, 2023
a4832d1
page poll relation results
Jan 17, 2023
10117e7
validate poll end event senders
Jan 17, 2023
0a618a2
reformatted copyright
Jan 17, 2023
68291e8
undo more comment reformatting
Jan 17, 2023
9c239b2
Merge branch 'develop' into psg-1014/poll-model-only-valid-end-events
Jan 17, 2023
48ea040
Merge branch 'psg-1014/poll-model-only-valid-end-events' into psg-101…
Jan 17, 2023
8e90212
test paging
Jan 17, 2023
7588f07
Merge branch 'develop' into psg-1014/poll-model-only-valid-end-events
Jan 26, 2023
0d965e3
Merge branch 'psg-1014/poll-model-only-valid-end-events' into psg-101…
Jan 26, 2023
9996113
use correct pollstartevent type
Jan 26, 2023
ed93046
emit after updating _isFetchingResponses state
Jan 27, 2023
a2fc0b9
Merge branch 'develop' into psg-1014/poll-model-only-valid-end-events
Jan 29, 2023
35c5b32
Merge branch 'psg-1014/poll-model-only-valid-end-events' into psg-101…
Jan 29, 2023
48db239
make rootEvent public readonly
Jan 30, 2023
4b80253
fix poll end validation logic to allow poll creator to end poll regar…
Jan 31, 2023
e2fc68a
Merge branch 'develop' into psg-1014/poll-relations-paging
Feb 1, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 176 additions & 24 deletions spec/unit/models/poll.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,24 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { IEvent, MatrixEvent, PollEvent } from "../../../src";
import { IEvent, MatrixEvent, PollEvent, Room } from "../../../src";
import { REFERENCE_RELATION } from "../../../src/@types/extensible_events";
import { M_POLL_END, M_POLL_KIND_DISCLOSED, M_POLL_RESPONSE } from "../../../src/@types/polls";
import { PollStartEvent } from "../../../src/extensible_events_v1/PollStartEvent";
import { Poll } from "../../../src/models/poll";
import { getMockClientWithEventEmitter } from "../../test-utils/client";
import { getMockClientWithEventEmitter, mockClientMethodsUser } from "../../test-utils/client";

jest.useFakeTimers();

describe("Poll", () => {
const userId = "@alice:server.org";
const mockClient = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
relations: jest.fn(),
});
const roomId = "!room:server";
const room = new Room(roomId, mockClient, userId);
const maySendRedactionForEventSpy = jest.spyOn(room.currentState, "maySendRedactionForEvent");
// 14.03.2022 16:15
const now = 1647270879403;

Expand All @@ -41,7 +45,9 @@ describe("Poll", () => {
jest.clearAllMocks();
jest.setSystemTime(now);

mockClient.relations.mockResolvedValue({ events: [] });
mockClient.relations.mockReset().mockResolvedValue({ events: [] });

maySendRedactionForEventSpy.mockClear().mockReturnValue(true);
});

let eventId = 1;
Expand All @@ -62,7 +68,7 @@ describe("Poll", () => {
};

it("initialises with root event", () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
expect(poll.roomId).toEqual(roomId);
expect(poll.pollId).toEqual(basePollStartEvent.getId());
expect(poll.pollEvent).toEqual(basePollStartEvent.unstableExtensibleEvent);
Expand All @@ -73,28 +79,37 @@ describe("Poll", () => {
const pollStartEvent = new MatrixEvent(
PollStartEvent.from("What?", ["a", "b"], M_POLL_KIND_DISCLOSED.name).serialize(),
);
expect(() => new Poll(pollStartEvent, mockClient)).toThrowError("Invalid poll start event.");
expect(() => new Poll(pollStartEvent, mockClient, room)).toThrowError("Invalid poll start event.");
});

it("throws when poll start has no event id", () => {
const pollStartEvent = new MatrixEvent({
...PollStartEvent.from("What?", ["a", "b"], M_POLL_KIND_DISCLOSED.name).serialize(),
room_id: roomId,
});
expect(() => new Poll(pollStartEvent, mockClient)).toThrowError("Invalid poll start event.");
expect(() => new Poll(pollStartEvent, mockClient, room)).toThrowError("Invalid poll start event.");
});

describe("fetching responses", () => {
it("calls relations api and emits", async () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
const emitSpy = jest.spyOn(poll, "emit");
const responses = await poll.getResponses();
expect(mockClient.relations).toHaveBeenCalledWith(roomId, basePollStartEvent.getId(), "m.reference");
const fetchResponsePromise = poll.getResponses();
expect(poll.isFetchingResponses).toBe(true);
const responses = await fetchResponsePromise;
expect(poll.isFetchingResponses).toBe(false);
expect(mockClient.relations).toHaveBeenCalledWith(
roomId,
basePollStartEvent.getId(),
"m.reference",
undefined,
{ from: undefined },
);
expect(emitSpy).toHaveBeenCalledWith(PollEvent.Responses, responses);
});

it("returns existing responses object after initial fetch", async () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
const responses = await poll.getResponses();
const responses2 = await poll.getResponses();
// only fetched relations once
Expand All @@ -104,7 +119,7 @@ describe("Poll", () => {
});

it("waits for existing relations request to finish when getting responses", async () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
const firstResponsePromise = poll.getResponses();
const secondResponsePromise = poll.getResponses();
await firstResponsePromise;
Expand All @@ -121,14 +136,56 @@ describe("Poll", () => {
mockClient.relations.mockResolvedValue({
events: [replyEvent, stableResponseEvent, unstableResponseEvent],
});
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
const responses = await poll.getResponses();
expect(responses.getRelations()).toEqual([stableResponseEvent, unstableResponseEvent]);
});

describe("with multiple pages of relations", () => {
const makeResponses = (count = 1, timestamp = now): MatrixEvent[] =>
new Array(count)
.fill("x")
.map((_x, index) =>
makeRelatedEvent(
{ type: M_POLL_RESPONSE.stable!, sender: "@bob@server.org" },
timestamp + index,
),
);

it("page relations responses", async () => {
const responseEvents = makeResponses(6);
mockClient.relations
.mockResolvedValueOnce({
events: responseEvents.slice(0, 2),
nextBatch: "test-next-1",
})
.mockResolvedValueOnce({
events: responseEvents.slice(2, 4),
nextBatch: "test-next-2",
})
.mockResolvedValueOnce({
events: responseEvents.slice(4),
});

const poll = new Poll(basePollStartEvent, mockClient, room);
jest.spyOn(poll, "emit");
const responses = await poll.getResponses();

expect(mockClient.relations.mock.calls).toEqual([
[roomId, basePollStartEvent.getId(), "m.reference", undefined, { from: undefined }],
[roomId, basePollStartEvent.getId(), "m.reference", undefined, { from: "test-next-1" }],
[roomId, basePollStartEvent.getId(), "m.reference", undefined, { from: "test-next-2" }],
]);

expect(poll.emit).toHaveBeenCalledTimes(3);
expect(poll.isFetchingResponses).toBeFalsy();
expect(responses.getRelations().length).toEqual(6);
});
});

describe("with poll end event", () => {
const stablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.stable! });
const unstablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.unstable! });
const stablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.stable!, sender: "@bob@server.org" });
const unstablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.unstable!, sender: "@bob@server.org" });
const responseEventBeforeEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now - 1000);
const responseEventAtEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now);
const responseEventAfterEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now + 1000);
Expand All @@ -140,19 +197,31 @@ describe("Poll", () => {
});

it("sets poll end event with stable event type", async () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
jest.spyOn(poll, "emit");
await poll.getResponses();

expect(maySendRedactionForEventSpy).toHaveBeenCalledWith(basePollStartEvent, "@bob@server.org");
expect(poll.isEnded).toBe(true);
expect(poll.emit).toHaveBeenCalledWith(PollEvent.End);
});

it("does not set poll end event when sent by invalid user", async () => {
const poll = new Poll(basePollStartEvent, mockClient, room);
maySendRedactionForEventSpy.mockReturnValue(false);
jest.spyOn(poll, "emit");
await poll.getResponses();

expect(maySendRedactionForEventSpy).toHaveBeenCalledWith(basePollStartEvent, "@bob@server.org");
expect(poll.isEnded).toBe(false);
expect(poll.emit).not.toHaveBeenCalledWith(PollEvent.End);
});

it("sets poll end event with unstable event type", async () => {
mockClient.relations.mockResolvedValue({
events: [unstablePollEndEvent],
});
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
jest.spyOn(poll, "emit");
await poll.getResponses();

Expand All @@ -161,7 +230,7 @@ describe("Poll", () => {
});

it("filters out responses that were sent after poll end", async () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
const responses = await poll.getResponses();

// just response type events
Expand All @@ -173,7 +242,7 @@ describe("Poll", () => {

describe("onNewRelation()", () => {
it("discards response if poll responses have not been initialised", () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
jest.spyOn(poll, "emit");
const responseEvent = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now);

Expand All @@ -184,24 +253,107 @@ describe("Poll", () => {
});

it("sets poll end event when responses are not initialised", () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
jest.spyOn(poll, "emit");
const stablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.stable! });
const stablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.stable!, sender: userId });

poll.onNewRelation(stablePollEndEvent);

expect(poll.emit).toHaveBeenCalledWith(PollEvent.End);
});

it("does not set poll end event when sent by invalid user", async () => {
maySendRedactionForEventSpy.mockReturnValue(false);
const stablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.stable!, sender: "@charlie:server.org" });
const responseEventAfterEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now + 1000);
mockClient.relations.mockResolvedValue({
events: [responseEventAfterEnd],
});
const poll = new Poll(basePollStartEvent, mockClient, room);
await poll.getResponses();
jest.spyOn(poll, "emit");

poll.onNewRelation(stablePollEndEvent);

// didn't end, didn't refilter responses
expect(poll.emit).not.toHaveBeenCalled();
expect(poll.isEnded).toBeFalsy();
expect(maySendRedactionForEventSpy).toHaveBeenCalledWith(basePollStartEvent, "@charlie:server.org");
});

it("does not set poll end event when an earlier end event already exists", async () => {
const earlierPollEndEvent = makeRelatedEvent(
{ type: M_POLL_END.stable!, sender: "@valid:server.org" },
now,
);
const laterPollEndEvent = makeRelatedEvent(
{ type: M_POLL_END.stable!, sender: "@valid:server.org" },
now + 2000,
);

const poll = new Poll(basePollStartEvent, mockClient, room);
await poll.getResponses();

poll.onNewRelation(earlierPollEndEvent);

// first end event set correctly
expect(poll.isEnded).toBeTruthy();

// reset spy count
jest.spyOn(poll, "emit").mockClear();

poll.onNewRelation(laterPollEndEvent);
// didn't set new end event, didn't refilter responses
expect(poll.emit).not.toHaveBeenCalled();
expect(poll.isEnded).toBeTruthy();
});

it("replaces poll end event and refilters when an older end event already exists", async () => {
const earlierPollEndEvent = makeRelatedEvent(
{ type: M_POLL_END.stable!, sender: "@valid:server.org" },
now,
);
const laterPollEndEvent = makeRelatedEvent(
{ type: M_POLL_END.stable!, sender: "@valid:server.org" },
now + 2000,
);
const responseEventBeforeEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now - 1000);
const responseEventAtEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now);
const responseEventAfterEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now + 1000);
mockClient.relations.mockResolvedValue({
events: [responseEventAfterEnd, responseEventAtEnd, responseEventBeforeEnd, laterPollEndEvent],
});

const poll = new Poll(basePollStartEvent, mockClient, room);
const responses = await poll.getResponses();

// all responses have a timestamp < laterPollEndEvent
expect(responses.getRelations().length).toEqual(3);
// first end event set correctly
expect(poll.isEnded).toBeTruthy();

// reset spy count
jest.spyOn(poll, "emit").mockClear();

// add a valid end event with earlier timestamp
poll.onNewRelation(earlierPollEndEvent);

// emitted new end event
expect(poll.emit).toHaveBeenCalledWith(PollEvent.End);
// filtered responses and emitted
expect(poll.emit).toHaveBeenCalledWith(PollEvent.Responses, responses);
expect(responses.getRelations()).toEqual([responseEventAtEnd, responseEventBeforeEnd]);
});

it("sets poll end event and refilters responses based on timestamp", async () => {
const stablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.stable! });
const stablePollEndEvent = makeRelatedEvent({ type: M_POLL_END.stable!, sender: userId });
const responseEventBeforeEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now - 1000);
const responseEventAtEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now);
const responseEventAfterEnd = makeRelatedEvent({ type: M_POLL_RESPONSE.name }, now + 1000);
mockClient.relations.mockResolvedValue({
events: [responseEventAfterEnd, responseEventAtEnd, responseEventBeforeEnd],
});
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
const responses = await poll.getResponses();
jest.spyOn(poll, "emit");

Expand All @@ -216,7 +368,7 @@ describe("Poll", () => {
});

it("filters out irrelevant relations", async () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
// init responses
const responses = await poll.getResponses();
jest.spyOn(poll, "emit");
Expand All @@ -230,7 +382,7 @@ describe("Poll", () => {
});

it("adds poll response relations to responses", async () => {
const poll = new Poll(basePollStartEvent, mockClient);
const poll = new Poll(basePollStartEvent, mockClient, room);
// init responses
const responses = await poll.getResponses();
jest.spyOn(poll, "emit");
Expand Down
Loading