Skip to content

Commit

Permalink
[@dhealthdapps/frontend] feat(test): improve base gateway tests, add …
Browse files Browse the repository at this point in the history
…auth gateway tests
  • Loading branch information
kravchenkodhealth authored and evias committed Jan 3, 2023
1 parent 6eff5f8 commit 15f042e
Show file tree
Hide file tree
Showing 7 changed files with 310 additions and 53 deletions.
2 changes: 1 addition & 1 deletion runtime/backend/src/common/gateways/AuthGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export class AuthGateway extends BaseGateway {
* @returns {void} Emits "auth.open" event which triggers validating of the received challenge
*/
@OnEvent("auth.open")
handleEvent(payload: any) {
handleAuthOpen(payload: any) {
this.validateChallengeScheduler.startCronJob(payload.challenge);
}

Expand Down
5 changes: 4 additions & 1 deletion runtime/backend/src/common/services/AuthService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const conf = dappConfigLoader();
* name: "ELEVATE",
* domain: "elevate.dhealth.com",
* secret: "AuthSecretUsedToSignCookies",
* challenge: "fakeChallenge"
* } as CookiePayload;
* ```
*
Expand All @@ -76,6 +77,7 @@ export interface CookiePayload {
name: string;
domain: string;
secret?: string;
challenge?: string;
}

/**
Expand Down Expand Up @@ -223,9 +225,10 @@ export class AuthService {
const name = this.configService.get<string>("dappName");
const domain = this.configService.get<string>("frontendApp.host");
const secret = this.configService.get<string>("auth.secret");
const challenge = this.configService.get<string>("challenge");

// configures cookie(s) creation
this.cookie = { name, domain, secret } as CookiePayload;
this.cookie = { name, domain, secret, challenge } as CookiePayload;
this.challengeSize = this.configService.get<number>("auth.challengeSize");
this.authSecret = secret;
}
Expand Down
17 changes: 12 additions & 5 deletions runtime/backend/tests/unit/common/ScopeFactory.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@ jest.mock("../../../src/users/UsersModule", () => {
});

// schedulers
const ValidateChallengeSchedulerMock: any = jest.fn();
jest.mock("../../../src/common/schedulers/ValidateChallengeScheduler", () => {
return { ValidateChallengeScheduler: ValidateChallengeSchedulerMock };
});

const DiscoverAccountsCommandMock: any = jest.fn();
jest.mock(
"../../../src/discovery/schedulers/DiscoverAccounts/DiscoverAccountsCommand",
Expand Down Expand Up @@ -205,7 +210,9 @@ const LeaderboardsAggregationCommandMock: any = jest.fn();
jest.mock(
"../../../src/statistics/schedulers/LeaderboardAggregation/LeaderboardsAggregationCommand",
() => {
return { LeaderboardsAggregationCommand: LeaderboardsAggregationCommandMock };
return {
LeaderboardsAggregationCommand: LeaderboardsAggregationCommandMock,
};
},
);

Expand All @@ -230,7 +237,7 @@ jest.mock(
"../../../src/payout/schedulers/ActivityPayouts/ActivityPayoutsCommand",
() => {
return { ActivityPayoutsCommand: ActivityPayoutsCommandMock };
}
},
);

const ReportNotifierCommandMock: any = { register: jest.fn() };
Expand All @@ -250,14 +257,14 @@ const mockDappConfig: DappConfig = {
url: "test-url",
host: "test-host",
port: "test-port",
https: false
https: false,
},
backendApp: {
url: "test-url",
host: "test-host",
port: "test-port",
https: false
}
https: false,
},
};

// internal dependencies
Expand Down
25 changes: 19 additions & 6 deletions runtime/backend/tests/unit/common/Scopes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,11 @@ jest.mock("../../../src/users/UsersModule", () => {
});

// schedulers
const ValidateChallengeSchedulerMock: any = jest.fn();
jest.mock("../../../src/common/schedulers/ValidateChallengeScheduler", () => {
return { ValidateChallengeScheduler: ValidateChallengeSchedulerMock };
});

const DiscoverAccountsCommandMock: any = jest.fn();
jest.mock(
"../../../src/discovery/schedulers/DiscoverAccounts/DiscoverAccountsCommand",
Expand Down Expand Up @@ -199,7 +204,9 @@ const LeaderboardsAggregationCommandMock: any = jest.fn();
jest.mock(
"../../../src/statistics/schedulers/LeaderboardAggregation/LeaderboardsAggregationCommand",
() => {
return { LeaderboardsAggregationCommand: LeaderboardsAggregationCommandMock };
return {
LeaderboardsAggregationCommand: LeaderboardsAggregationCommandMock,
};
},
);

Expand All @@ -224,7 +231,7 @@ jest.mock(
"../../../src/payout/schedulers/ActivityPayouts/ActivityPayoutsCommand",
() => {
return { ActivityPayoutsCommand: ActivityPayoutsCommandMock };
}
},
);

const ReportNotifierCommandMock: any = { register: jest.fn() };
Expand All @@ -251,22 +258,28 @@ class MockFactory extends ScopeFactory {
}

describe("common/Scopes", () => {
let dappConfig: any,
actualModules: any[];
let dappConfig: any, actualModules: any[];
beforeEach(() => {
// prepare for all (includes database scope)
dappConfig = {
dappName: "Fake dApp",
dappPublicKey: "FakePublicKeyOfAdApp",
authAuthority: "NonExistingAuthority",
scopes: ["database"],
database: { host: "fake-host", port: 1234, name: "fake-db-name", user: "fake-user" },
database: {
host: "fake-host",
port: 1234,
name: "fake-db-name",
user: "fake-user",
},
};
});

it("should use environment variables from mocks", () => {
// assert
expect(process.env.ANOTHER_DB_NAME_THROUGH_ENV).toEqual("this-exists-only-in-mock");
expect(process.env.ANOTHER_DB_NAME_THROUGH_ENV).toEqual(
"this-exists-only-in-mock",
);
});

it("should include database scope in enabled modules", () => {
Expand Down
116 changes: 116 additions & 0 deletions runtime/backend/tests/unit/common/gateways/AuthGateway.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/**
* This file is part of dHealth dApps Framework shared under LGPL-3.0
* Copyright (C) 2022-present dHealth Network, All rights reserved.
*
* @package dHealth dApps Framework
* @subpackage Backend
* @author dHealth Network <[email protected]>
* @license LGPL-3.0
*/

// external dependencies
import { TestingModule, Test } from "@nestjs/testing";
import { EventEmitter2 } from "@nestjs/event-emitter";
import { SchedulerRegistry } from "@nestjs/schedule";
import { ConfigService } from "@nestjs/config";
import { JwtService } from "@nestjs/jwt";

// internal dependencies
import { ValidateChallengeScheduler } from "../../../../src/common/schedulers/ValidateChallengeScheduler";
import { AuthGateway } from "../../../../src/common/gateways/AuthGateway";
import { AuthService } from "../../../../src/common/services/AuthService";
import { NetworkService } from "../../../../src/common/services/NetworkService";
import { AccountsService } from "../../../../src/common/services/AccountsService";
import { ChallengesService } from "../../../../src/common/services/ChallengesService";
import { QueryService } from "../../../../src/common/services/QueryService";
import { MockModel } from "../../../mocks/global";
import { getModelToken } from "@nestjs/mongoose";

describe("common/AuthGateway", () => {
let authGateway: AuthGateway;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
EventEmitter2,
ValidateChallengeScheduler,
AuthGateway,
SchedulerRegistry,
AuthService,
ConfigService,
NetworkService,
AccountsService,
ChallengesService,
QueryService,
JwtService,
{
provide: getModelToken("Account"),
useValue: MockModel,
}, // requirement from AccountsService
{
provide: getModelToken("AuthChallenge"),
useValue: MockModel,
},
],
}).compile();

authGateway = module.get<AuthGateway>(AuthGateway);
});

it("should be defined", () => {
expect(authGateway).toBeDefined();
});

describe("constructor()", () => {
it("should initialize emitter", () => {
expect("emitter" in authGateway).toBe(true);
});

it("should initialize validateChallengeScheduler", () => {
expect("validateChallengeScheduler" in authGateway).toBe(true);
});
});

describe("handleAuthOpen()", () => {
it("should start validation of challenge", () => {
const validateMethodMock = jest.fn();

(authGateway as any).validateChallengeScheduler = {
startCronJob: validateMethodMock,
};

authGateway.handleAuthOpen({ challenge: "fakeChallenge" });

expect(validateMethodMock).toBeCalledTimes(1);
});
});

describe("complete()", () => {
it("should send complete message to client and log message", () => {
const mockedMethod = jest.fn();

(authGateway as any).ws = {
send: mockedMethod,
};
(authGateway as any).logger = {
log: mockedMethod,
};

authGateway.complete();
expect(mockedMethod).toBeCalledTimes(2);
});
});

describe("close", () => {
it("should log message on close", () => {
const mockedMethod = jest.fn();

(authGateway as any).logger = {
log: mockedMethod,
};

authGateway.close();
expect(mockedMethod).toBeCalledTimes(1);
});
});
});
Loading

0 comments on commit 15f042e

Please sign in to comment.