1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-01-11 18:24:43 +02:00

Server: Added test units for user login

This commit is contained in:
Laurent Cozic 2021-01-12 17:14:09 +00:00
parent c70f023fe0
commit 59fa51c5bf
3 changed files with 68 additions and 1 deletions

View File

@ -0,0 +1,47 @@
import { createUserAndSession, beforeAllDb, afterAllDb, beforeEachDb, koaAppContext, koaNext } from '../utils/testing/testUtils';
import ownerHandler from './ownerHandler';
describe('ownerHandler', function() {
beforeAll(async () => {
await beforeAllDb('ownerHandler');
});
afterAll(async () => {
await afterAllDb();
});
beforeEach(async () => {
await beforeEachDb();
});
test('should login user with valid session ID', async function() {
const { user, session } = await createUserAndSession(1, false);
const context = await koaAppContext({
sessionId: session.id,
});
expect(!!context.owner).toBe(false);
await ownerHandler(context, koaNext);
expect(!!context.owner).toBe(true);
expect(context.owner.id).toBe(user.id);
});
test('should not login user with invalid session ID', async function() {
await createUserAndSession(1, false);
const context = await koaAppContext({
sessionId: 'ihack',
});
expect(!!context.owner).toBe(false);
await ownerHandler(context, koaNext);
expect(!!context.owner).toBe(false);
});
});

View File

@ -2,7 +2,7 @@ import { AppContext, KoaNext } from '../utils/types';
import { isApiRequest, contextSessionId } from '../utils/requestUtils';
import Logger from '@joplin/lib/Logger';
const logger = Logger.create('loggedInUserHandler');
const logger = Logger.create('ownerHandler');
export default async function(ctx: AppContext, next: KoaNext): Promise<void> {
try {

View File

@ -42,6 +42,7 @@ export async function beforeEachDb() {
interface AppContextTestOptions {
path?: string;
owner?: User;
sessionId?: string;
}
let koaAppContextUserAndSession_: UserAndSession = null;
@ -52,6 +53,20 @@ export async function koaAppContextUserAndSession(): Promise<UserAndSession> {
return koaAppContextUserAndSession_;
}
class FakeCookies {
private values_: Record<string, string> = {};
public get(name: string): string {
return this.values_[name];
}
public set(name: string, value: string) {
this.values_[name] = value;
}
}
export async function koaAppContext(options: AppContextTestOptions = null): Promise<AppContext> {
if (!db_) throw new Error('Database must be initialized first');
@ -72,6 +87,11 @@ export async function koaAppContext(options: AppContextTestOptions = null): Prom
appContext.path = options.path;
appContext.owner = options.owner;
appContext.cookies = new FakeCookies();
if (options.sessionId) {
appContext.cookies.set('sessionId', options.sessionId);
}
return appContext as AppContext;
}