Fix tests with using sessions in e2e tests of private api

Signed-off-by: Yannick Bungers <git@innay.de>
This commit is contained in:
Yannick Bungers 2021-10-13 20:43:56 +02:00 committed by David Mehren
parent ad190fcf22
commit 11ae7d133c
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
6 changed files with 132 additions and 88 deletions

View file

@ -22,7 +22,7 @@ module.exports = {
'jest/expect-expect': [ 'jest/expect-expect': [
'error', 'error',
{ {
assertFunctionNames: ['expect', 'request.**.expect'], assertFunctionNames: ['expect', 'request.**.expect', 'agent.**.expect'],
}, },
], ],
'jest/no-standalone-expect': [ 'jest/no-standalone-expect': [

View file

@ -11,12 +11,14 @@ import request from 'supertest';
import { PrivateApiModule } from '../../src/api/private/private-api.module'; import { PrivateApiModule } from '../../src/api/private/private-api.module';
import { AuthModule } from '../../src/auth/auth.module'; import { AuthModule } from '../../src/auth/auth.module';
import { AuthConfig } from '../../src/config/auth.config';
import appConfigMock from '../../src/config/mock/app.config.mock'; import appConfigMock from '../../src/config/mock/app.config.mock';
import authConfigMock from '../../src/config/mock/auth.config.mock'; import authConfigMock from '../../src/config/mock/auth.config.mock';
import customizationConfigMock from '../../src/config/mock/customization.config.mock'; import customizationConfigMock from '../../src/config/mock/customization.config.mock';
import externalConfigMock from '../../src/config/mock/external-services.config.mock'; import externalConfigMock from '../../src/config/mock/external-services.config.mock';
import mediaConfigMock from '../../src/config/mock/media.config.mock'; import mediaConfigMock from '../../src/config/mock/media.config.mock';
import { GroupsModule } from '../../src/groups/groups.module'; import { GroupsModule } from '../../src/groups/groups.module';
import { IdentityService } from '../../src/identity/identity.service';
import { LoggerModule } from '../../src/logger/logger.module'; import { LoggerModule } from '../../src/logger/logger.module';
import { AliasCreateDto } from '../../src/notes/alias-create.dto'; import { AliasCreateDto } from '../../src/notes/alias-create.dto';
import { AliasUpdateDto } from '../../src/notes/alias-update.dto'; import { AliasUpdateDto } from '../../src/notes/alias-update.dto';
@ -27,14 +29,17 @@ import { PermissionsModule } from '../../src/permissions/permissions.module';
import { User } from '../../src/users/user.entity'; import { User } from '../../src/users/user.entity';
import { UsersModule } from '../../src/users/users.module'; import { UsersModule } from '../../src/users/users.module';
import { UsersService } from '../../src/users/users.service'; import { UsersService } from '../../src/users/users.service';
import { setupSessionMiddleware } from '../../src/utils/session';
describe('Alias', () => { describe('Alias', () => {
let app: INestApplication; let app: INestApplication;
let aliasService: AliasService; let aliasService: AliasService;
let notesService: NotesService; let notesService: NotesService;
let identityService: IdentityService;
let user: User; let user: User;
let content: string; let content: string;
let forbiddenNoteId: string; let forbiddenNoteId: string;
let agent: request.SuperAgentTest;
beforeAll(async () => { beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
@ -69,12 +74,21 @@ describe('Alias', () => {
const config = moduleRef.get<ConfigService>(ConfigService); const config = moduleRef.get<ConfigService>(ConfigService);
forbiddenNoteId = config.get('appConfig').forbiddenNoteIds[0]; forbiddenNoteId = config.get('appConfig').forbiddenNoteIds[0];
app = moduleRef.createNestApplication(); app = moduleRef.createNestApplication();
const authConfig = config.get('authConfig') as AuthConfig;
setupSessionMiddleware(app, authConfig);
await app.init(); await app.init();
aliasService = moduleRef.get(AliasService); aliasService = moduleRef.get(AliasService);
notesService = moduleRef.get(NotesService); notesService = moduleRef.get(NotesService);
identityService = moduleRef.get(IdentityService);
const userService = moduleRef.get(UsersService); const userService = moduleRef.get(UsersService);
user = await userService.createUser('hardcoded', 'Testy'); user = await userService.createUser('hardcoded', 'Testy');
await identityService.createLocalIdentity(user, 'test');
content = 'This is a test note.'; content = 'This is a test note.';
agent = request.agent(app.getHttpServer());
await agent
.post('/auth/local/login')
.send({ username: 'hardcoded', password: 'test' })
.expect(201);
}); });
describe('POST /alias', () => { describe('POST /alias', () => {
@ -92,7 +106,7 @@ describe('Alias', () => {
it('create with normal alias', async () => { it('create with normal alias', async () => {
const newAlias = 'normalAlias'; const newAlias = 'normalAlias';
newAliasDto.newAlias = newAlias; newAliasDto.newAlias = newAlias;
const metadata = await request(app.getHttpServer()) const metadata = await agent
.post(`/alias`) .post(`/alias`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(newAliasDto) .send(newAliasDto)
@ -100,9 +114,7 @@ describe('Alias', () => {
expect(metadata.body.name).toEqual(newAlias); expect(metadata.body.name).toEqual(newAlias);
expect(metadata.body.primaryAlias).toBeFalsy(); expect(metadata.body.primaryAlias).toBeFalsy();
expect(metadata.body.noteId).toEqual(publicId); expect(metadata.body.noteId).toEqual(publicId);
const note = await request(app.getHttpServer()) const note = await agent.get(`/notes/${newAlias}`).expect(200);
.get(`/notes/${newAlias}`)
.expect(200);
expect(note.body.metadata.aliases).toContain(newAlias); expect(note.body.metadata.aliases).toContain(newAlias);
expect(note.body.metadata.primaryAlias).toBeTruthy(); expect(note.body.metadata.primaryAlias).toBeTruthy();
expect(note.body.metadata.id).toEqual(publicId); expect(note.body.metadata.id).toEqual(publicId);
@ -111,7 +123,7 @@ describe('Alias', () => {
describe('does not create an alias', () => { describe('does not create an alias', () => {
it('because of a forbidden alias', async () => { it('because of a forbidden alias', async () => {
newAliasDto.newAlias = forbiddenNoteId; newAliasDto.newAlias = forbiddenNoteId;
await request(app.getHttpServer()) await agent
.post(`/alias`) .post(`/alias`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(newAliasDto) .send(newAliasDto)
@ -119,7 +131,7 @@ describe('Alias', () => {
}); });
it('because of a alias that is a public id', async () => { it('because of a alias that is a public id', async () => {
newAliasDto.newAlias = publicId; newAliasDto.newAlias = publicId;
await request(app.getHttpServer()) await agent
.post(`/alias`) .post(`/alias`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(newAliasDto) .send(newAliasDto)
@ -142,7 +154,7 @@ describe('Alias', () => {
}); });
it('updates a note with a normal alias', async () => { it('updates a note with a normal alias', async () => {
const metadata = await request(app.getHttpServer()) const metadata = await agent
.put(`/alias/${newAlias}`) .put(`/alias/${newAlias}`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(changeAliasDto) .send(changeAliasDto)
@ -150,9 +162,7 @@ describe('Alias', () => {
expect(metadata.body.name).toEqual(newAlias); expect(metadata.body.name).toEqual(newAlias);
expect(metadata.body.primaryAlias).toBeTruthy(); expect(metadata.body.primaryAlias).toBeTruthy();
expect(metadata.body.noteId).toEqual(publicId); expect(metadata.body.noteId).toEqual(publicId);
const note = await request(app.getHttpServer()) const note = await agent.get(`/notes/${newAlias}`).expect(200);
.get(`/notes/${newAlias}`)
.expect(200);
expect(note.body.metadata.aliases).toContain(newAlias); expect(note.body.metadata.aliases).toContain(newAlias);
expect(note.body.metadata.primaryAlias).toBeTruthy(); expect(note.body.metadata.primaryAlias).toBeTruthy();
expect(note.body.metadata.id).toEqual(publicId); expect(note.body.metadata.id).toEqual(publicId);
@ -160,7 +170,7 @@ describe('Alias', () => {
describe('does not update', () => { describe('does not update', () => {
it('a note with unknown alias', async () => { it('a note with unknown alias', async () => {
await request(app.getHttpServer()) await agent
.put(`/alias/i_dont_exist`) .put(`/alias/i_dont_exist`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(changeAliasDto) .send(changeAliasDto)
@ -168,7 +178,7 @@ describe('Alias', () => {
}); });
it('if the property primaryAlias is false', async () => { it('if the property primaryAlias is false', async () => {
changeAliasDto.primaryAlias = false; changeAliasDto.primaryAlias = false;
await request(app.getHttpServer()) await agent
.put(`/alias/${newAlias}`) .put(`/alias/${newAlias}`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(changeAliasDto) .send(changeAliasDto)
@ -186,34 +196,24 @@ describe('Alias', () => {
}); });
it('deletes a normal alias', async () => { it('deletes a normal alias', async () => {
await request(app.getHttpServer()) await agent.delete(`/alias/${newAlias}`).expect(204);
.delete(`/alias/${newAlias}`) await agent.get(`/notes/${newAlias}`).expect(404);
.expect(204);
await request(app.getHttpServer()).get(`/notes/${newAlias}`).expect(404);
}); });
it('does not delete an unknown alias', async () => { it('does not delete an unknown alias', async () => {
await request(app.getHttpServer()) await agent.delete(`/alias/i_dont_exist`).expect(404);
.delete(`/alias/i_dont_exist`)
.expect(404);
}); });
it('does not delete an primary alias (if it is not the only one)', async () => { it('does not delete an primary alias (if it is not the only one)', async () => {
const note = await notesService.getNoteByIdOrAlias(testAlias); const note = await notesService.getNoteByIdOrAlias(testAlias);
await aliasService.addAlias(note, newAlias); await aliasService.addAlias(note, newAlias);
await request(app.getHttpServer()) await agent.delete(`/alias/${testAlias}`).expect(400);
.delete(`/alias/${testAlias}`) await agent.get(`/notes/${newAlias}`).expect(200);
.expect(400);
await request(app.getHttpServer()).get(`/notes/${newAlias}`).expect(200);
}); });
it('deletes a primary alias (if it is the only one)', async () => { it('deletes a primary alias (if it is the only one)', async () => {
await request(app.getHttpServer()) await agent.delete(`/alias/${newAlias}`).expect(204);
.delete(`/alias/${newAlias}`) await agent.delete(`/alias/${testAlias}`).expect(204);
.expect(204);
await request(app.getHttpServer())
.delete(`/alias/${testAlias}`)
.expect(204);
}); });
}); });
}); });

View file

@ -11,6 +11,7 @@ import request from 'supertest';
import { PrivateApiModule } from '../../src/api/private/private-api.module'; import { PrivateApiModule } from '../../src/api/private/private-api.module';
import { AuthModule } from '../../src/auth/auth.module'; import { AuthModule } from '../../src/auth/auth.module';
import { AuthConfig } from '../../src/config/auth.config';
import appConfigMock from '../../src/config/mock/app.config.mock'; import appConfigMock from '../../src/config/mock/app.config.mock';
import authConfigMock from '../../src/config/mock/auth.config.mock'; import authConfigMock from '../../src/config/mock/auth.config.mock';
import customizationConfigMock from '../../src/config/mock/customization.config.mock'; import customizationConfigMock from '../../src/config/mock/customization.config.mock';
@ -20,6 +21,7 @@ import { GroupsModule } from '../../src/groups/groups.module';
import { HistoryEntryImportDto } from '../../src/history/history-entry-import.dto'; import { HistoryEntryImportDto } from '../../src/history/history-entry-import.dto';
import { HistoryEntry } from '../../src/history/history-entry.entity'; import { HistoryEntry } from '../../src/history/history-entry.entity';
import { HistoryService } from '../../src/history/history.service'; import { HistoryService } from '../../src/history/history.service';
import { IdentityService } from '../../src/identity/identity.service';
import { LoggerModule } from '../../src/logger/logger.module'; import { LoggerModule } from '../../src/logger/logger.module';
import { Note } from '../../src/notes/note.entity'; import { Note } from '../../src/notes/note.entity';
import { NotesModule } from '../../src/notes/notes.module'; import { NotesModule } from '../../src/notes/notes.module';
@ -28,15 +30,18 @@ import { PermissionsModule } from '../../src/permissions/permissions.module';
import { User } from '../../src/users/user.entity'; import { User } from '../../src/users/user.entity';
import { UsersModule } from '../../src/users/users.module'; import { UsersModule } from '../../src/users/users.module';
import { UsersService } from '../../src/users/users.service'; import { UsersService } from '../../src/users/users.service';
import { setupSessionMiddleware } from '../../src/utils/session';
describe('History', () => { describe('History', () => {
let app: INestApplication; let app: INestApplication;
let historyService: HistoryService; let historyService: HistoryService;
let identityService: IdentityService;
let user: User; let user: User;
let note: Note; let note: Note;
let note2: Note; let note2: Note;
let forbiddenNoteId: string; let forbiddenNoteId: string;
let content: string; let content: string;
let agent: request.SuperAgentTest;
beforeAll(async () => { beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
@ -71,25 +76,34 @@ describe('History', () => {
const config = moduleRef.get<ConfigService>(ConfigService); const config = moduleRef.get<ConfigService>(ConfigService);
forbiddenNoteId = config.get('appConfig').forbiddenNoteIds[0]; forbiddenNoteId = config.get('appConfig').forbiddenNoteIds[0];
app = moduleRef.createNestApplication(); app = moduleRef.createNestApplication();
const authConfig = config.get('authConfig') as AuthConfig;
setupSessionMiddleware(app, authConfig);
await app.init(); await app.init();
content = 'This is a test note.'; content = 'This is a test note.';
historyService = moduleRef.get(HistoryService); historyService = moduleRef.get(HistoryService);
const userService = moduleRef.get(UsersService); const userService = moduleRef.get(UsersService);
identityService = moduleRef.get(IdentityService);
user = await userService.createUser('hardcoded', 'Testy'); user = await userService.createUser('hardcoded', 'Testy');
await identityService.createLocalIdentity(user, 'test');
const notesService = moduleRef.get(NotesService); const notesService = moduleRef.get(NotesService);
note = await notesService.createNote(content, 'note', user); note = await notesService.createNote(content, 'note', user);
note2 = await notesService.createNote(content, 'note2', user); note2 = await notesService.createNote(content, 'note2', user);
agent = request.agent(app.getHttpServer());
await agent
.post('/auth/local/login')
.send({ username: 'hardcoded', password: 'test' })
.expect(201);
}); });
it('GET /me/history', async () => { it('GET /me/history', async () => {
const emptyResponse = await request(app.getHttpServer()) const emptyResponse = await agent
.get('/me/history') .get('/me/history')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
expect(emptyResponse.body.length).toEqual(0); expect(emptyResponse.body.length).toEqual(0);
const entry = await historyService.updateHistoryEntryTimestamp(note, user); const entry = await historyService.updateHistoryEntryTimestamp(note, user);
const entryDto = historyService.toHistoryEntryDto(entry); const entryDto = historyService.toHistoryEntryDto(entry);
const response = await request(app.getHttpServer()) const response = await agent
.get('/me/history') .get('/me/history')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
@ -114,7 +128,7 @@ describe('History', () => {
)[0].name; )[0].name;
postEntryDto.pinStatus = pinStatus; postEntryDto.pinStatus = pinStatus;
postEntryDto.lastVisited = lastVisited; postEntryDto.lastVisited = lastVisited;
await request(app.getHttpServer()) await agent
.post('/me/history') .post('/me/history')
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(JSON.stringify({ history: [postEntryDto] })) .send(JSON.stringify({ history: [postEntryDto] }))
@ -149,7 +163,7 @@ describe('History', () => {
brokenEntryDto.note = forbiddenNoteId; brokenEntryDto.note = forbiddenNoteId;
brokenEntryDto.pinStatus = pinStatus; brokenEntryDto.pinStatus = pinStatus;
brokenEntryDto.lastVisited = lastVisited; brokenEntryDto.lastVisited = lastVisited;
await request(app.getHttpServer()) await agent
.post('/me/history') .post('/me/history')
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(JSON.stringify({ history: [brokenEntryDto] })) .send(JSON.stringify({ history: [brokenEntryDto] }))
@ -160,7 +174,7 @@ describe('History', () => {
brokenEntryDto.note = 'i_dont_exist'; brokenEntryDto.note = 'i_dont_exist';
brokenEntryDto.pinStatus = pinStatus; brokenEntryDto.pinStatus = pinStatus;
brokenEntryDto.lastVisited = lastVisited; brokenEntryDto.lastVisited = lastVisited;
await request(app.getHttpServer()) await agent
.post('/me/history') .post('/me/history')
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send(JSON.stringify({ history: [brokenEntryDto] })) .send(JSON.stringify({ history: [brokenEntryDto] }))
@ -181,7 +195,7 @@ describe('History', () => {
it('DELETE /me/history', async () => { it('DELETE /me/history', async () => {
expect((await historyService.getEntriesByUser(user)).length).toEqual(1); expect((await historyService.getEntriesByUser(user)).length).toEqual(1);
await request(app.getHttpServer()).delete('/me/history').expect(200); await agent.delete('/me/history').expect(200);
expect((await historyService.getEntriesByUser(user)).length).toEqual(0); expect((await historyService.getEntriesByUser(user)).length).toEqual(0);
}); });
@ -189,7 +203,7 @@ describe('History', () => {
const entry = await historyService.updateHistoryEntryTimestamp(note2, user); const entry = await historyService.updateHistoryEntryTimestamp(note2, user);
expect(entry.pinStatus).toBeFalsy(); expect(entry.pinStatus).toBeFalsy();
const alias = entry.note.aliases.filter((alias) => alias.primary)[0].name; const alias = entry.note.aliases.filter((alias) => alias.primary)[0].name;
await request(app.getHttpServer()) await agent
.put(`/me/history/${alias || 'undefined'}`) .put(`/me/history/${alias || 'undefined'}`)
.send({ pinStatus: true }) .send({ pinStatus: true })
.expect(200); .expect(200);
@ -204,9 +218,7 @@ describe('History', () => {
const alias = entry.note.aliases.filter((alias) => alias.primary)[0].name; const alias = entry.note.aliases.filter((alias) => alias.primary)[0].name;
const entry2 = await historyService.updateHistoryEntryTimestamp(note, user); const entry2 = await historyService.updateHistoryEntryTimestamp(note, user);
const entryDto = historyService.toHistoryEntryDto(entry2); const entryDto = historyService.toHistoryEntryDto(entry2);
await request(app.getHttpServer()) await agent.delete(`/me/history/${alias || 'undefined'}`).expect(200);
.delete(`/me/history/${alias || 'undefined'}`)
.expect(200);
const userEntries = await historyService.getEntriesByUser(user); const userEntries = await historyService.getEntriesByUser(user);
expect(userEntries.length).toEqual(1); expect(userEntries.length).toEqual(1);
const userEntryDto = historyService.toHistoryEntryDto(userEntries[0]); const userEntryDto = historyService.toHistoryEntryDto(userEntries[0]);

View file

@ -17,6 +17,7 @@ import request from 'supertest';
import { PrivateApiModule } from '../../src/api/private/private-api.module'; import { PrivateApiModule } from '../../src/api/private/private-api.module';
import { AuthModule } from '../../src/auth/auth.module'; import { AuthModule } from '../../src/auth/auth.module';
import { AuthConfig } from '../../src/config/auth.config';
import appConfigMock from '../../src/config/mock/app.config.mock'; import appConfigMock from '../../src/config/mock/app.config.mock';
import authConfigMock from '../../src/config/mock/auth.config.mock'; import authConfigMock from '../../src/config/mock/auth.config.mock';
import customizationConfigMock from '../../src/config/mock/customization.config.mock'; import customizationConfigMock from '../../src/config/mock/customization.config.mock';
@ -25,6 +26,7 @@ import mediaConfigMock from '../../src/config/mock/media.config.mock';
import { NotInDBError } from '../../src/errors/errors'; import { NotInDBError } from '../../src/errors/errors';
import { GroupsModule } from '../../src/groups/groups.module'; import { GroupsModule } from '../../src/groups/groups.module';
import { HistoryModule } from '../../src/history/history.module'; import { HistoryModule } from '../../src/history/history.module';
import { IdentityService } from '../../src/identity/identity.service';
import { LoggerModule } from '../../src/logger/logger.module'; import { LoggerModule } from '../../src/logger/logger.module';
import { MediaModule } from '../../src/media/media.module'; import { MediaModule } from '../../src/media/media.module';
import { MediaService } from '../../src/media/media.service'; import { MediaService } from '../../src/media/media.service';
@ -36,17 +38,20 @@ import { UserInfoDto } from '../../src/users/user-info.dto';
import { User } from '../../src/users/user.entity'; import { User } from '../../src/users/user.entity';
import { UsersModule } from '../../src/users/users.module'; import { UsersModule } from '../../src/users/users.module';
import { UsersService } from '../../src/users/users.service'; import { UsersService } from '../../src/users/users.service';
import { setupSessionMiddleware } from '../../src/utils/session';
describe('Me', () => { describe('Me', () => {
let app: INestApplication; let app: INestApplication;
let userService: UsersService; let userService: UsersService;
let mediaService: MediaService; let mediaService: MediaService;
let identityService: IdentityService;
let uploadPath: string; let uploadPath: string;
let user: User; let user: User;
let content: string; let content: string;
let note1: Note; let note1: Note;
let alias2: string; let alias2: string;
let note2: Note; let note2: Note;
let agent: request.SuperAgentTest;
beforeAll(async () => { beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
@ -82,21 +87,31 @@ describe('Me', () => {
const config = moduleRef.get<ConfigService>(ConfigService); const config = moduleRef.get<ConfigService>(ConfigService);
uploadPath = config.get('mediaConfig').backend.filesystem.uploadPath; uploadPath = config.get('mediaConfig').backend.filesystem.uploadPath;
app = moduleRef.createNestApplication(); app = moduleRef.createNestApplication();
const authConfig = config.get('authConfig') as AuthConfig;
setupSessionMiddleware(app, authConfig);
await app.init(); await app.init();
//historyService = moduleRef.get(); //historyService = moduleRef.get();
userService = moduleRef.get(UsersService); userService = moduleRef.get(UsersService);
mediaService = moduleRef.get(MediaService); mediaService = moduleRef.get(MediaService);
identityService = moduleRef.get(IdentityService);
user = await userService.createUser('hardcoded', 'Testy'); user = await userService.createUser('hardcoded', 'Testy');
await identityService.createLocalIdentity(user, 'test');
const notesService = moduleRef.get(NotesService); const notesService = moduleRef.get(NotesService);
content = 'This is a test note.'; content = 'This is a test note.';
alias2 = 'note2'; alias2 = 'note2';
note1 = await notesService.createNote(content, undefined, user); note1 = await notesService.createNote(content, undefined, user);
note2 = await notesService.createNote(content, alias2, user); note2 = await notesService.createNote(content, alias2, user);
agent = request.agent(app.getHttpServer());
await agent
.post('/auth/local/login')
.send({ username: 'hardcoded', password: 'test' })
.expect(201);
}); });
it('GET /me', async () => { it('GET /me', async () => {
const userInfo = userService.toUserDto(user); const userInfo = userService.toUserDto(user);
const response = await request(app.getHttpServer()) const response = await agent
.get('/me') .get('/me')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
@ -105,8 +120,7 @@ describe('Me', () => {
}); });
it('GET /me/media', async () => { it('GET /me/media', async () => {
const httpServer = app.getHttpServer(); const responseBefore = await agent
const responseBefore = await request(httpServer)
.get('/me/media/') .get('/me/media/')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
@ -118,7 +132,7 @@ describe('Me', () => {
const url2 = await mediaService.saveFile(testImage, user, note2); const url2 = await mediaService.saveFile(testImage, user, note2);
const url3 = await mediaService.saveFile(testImage, user, note2); const url3 = await mediaService.saveFile(testImage, user, note2);
const response = await request(httpServer) const response = await agent
.get('/me/media/') .get('/me/media/')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
@ -137,7 +151,7 @@ describe('Me', () => {
it('POST /me/profile', async () => { it('POST /me/profile', async () => {
const newDisplayName = 'Another name'; const newDisplayName = 'Another name';
expect(user.displayName).not.toEqual(newDisplayName); expect(user.displayName).not.toEqual(newDisplayName);
await request(app.getHttpServer()) await agent
.post('/me/profile') .post('/me/profile')
.send({ .send({
name: newDisplayName, name: newDisplayName,
@ -155,7 +169,7 @@ describe('Me', () => {
const mediaUploads = await mediaService.listUploadsByUser(dbUser); const mediaUploads = await mediaService.listUploadsByUser(dbUser);
expect(mediaUploads).toHaveLength(1); expect(mediaUploads).toHaveLength(1);
expect(mediaUploads[0].fileUrl).toEqual(url0); expect(mediaUploads[0].fileUrl).toEqual(url0);
await request(app.getHttpServer()).delete('/me').expect(204); await agent.delete('/me').expect(204);
await expect(userService.getUserByUsername('hardcoded')).rejects.toThrow( await expect(userService.getUserByUsername('hardcoded')).rejects.toThrow(
NotInDBError, NotInDBError,
); );

View file

@ -13,12 +13,14 @@ import request from 'supertest';
import { PrivateApiModule } from '../../src/api/private/private-api.module'; import { PrivateApiModule } from '../../src/api/private/private-api.module';
import { AuthModule } from '../../src/auth/auth.module'; import { AuthModule } from '../../src/auth/auth.module';
import { AuthConfig } from '../../src/config/auth.config';
import appConfigMock from '../../src/config/mock/app.config.mock'; import appConfigMock from '../../src/config/mock/app.config.mock';
import authConfigMock from '../../src/config/mock/auth.config.mock'; import authConfigMock from '../../src/config/mock/auth.config.mock';
import customizationConfigMock from '../../src/config/mock/customization.config.mock'; import customizationConfigMock from '../../src/config/mock/customization.config.mock';
import externalConfigMock from '../../src/config/mock/external-services.config.mock'; import externalConfigMock from '../../src/config/mock/external-services.config.mock';
import mediaConfigMock from '../../src/config/mock/media.config.mock'; import mediaConfigMock from '../../src/config/mock/media.config.mock';
import { GroupsModule } from '../../src/groups/groups.module'; import { GroupsModule } from '../../src/groups/groups.module';
import { IdentityService } from '../../src/identity/identity.service';
import { ConsoleLoggerService } from '../../src/logger/console-logger.service'; import { ConsoleLoggerService } from '../../src/logger/console-logger.service';
import { LoggerModule } from '../../src/logger/logger.module'; import { LoggerModule } from '../../src/logger/logger.module';
import { MediaModule } from '../../src/media/media.module'; import { MediaModule } from '../../src/media/media.module';
@ -26,11 +28,14 @@ import { NotesModule } from '../../src/notes/notes.module';
import { NotesService } from '../../src/notes/notes.service'; import { NotesService } from '../../src/notes/notes.service';
import { PermissionsModule } from '../../src/permissions/permissions.module'; import { PermissionsModule } from '../../src/permissions/permissions.module';
import { UsersService } from '../../src/users/users.service'; import { UsersService } from '../../src/users/users.service';
import { setupSessionMiddleware } from '../../src/utils/session';
import { ensureDeleted } from '../utils'; import { ensureDeleted } from '../utils';
describe('Media', () => { describe('Media', () => {
let identityService: IdentityService;
let app: NestExpressApplication; let app: NestExpressApplication;
let uploadPath: string; let uploadPath: string;
let agent: request.SuperAgentTest;
beforeAll(async () => { beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
@ -67,19 +72,28 @@ describe('Media', () => {
app.useStaticAssets(uploadPath, { app.useStaticAssets(uploadPath, {
prefix: '/uploads', prefix: '/uploads',
}); });
const authConfig = config.get('authConfig') as AuthConfig;
setupSessionMiddleware(app, authConfig);
await app.init(); await app.init();
const logger = await app.resolve(ConsoleLoggerService); const logger = await app.resolve(ConsoleLoggerService);
logger.log('Switching logger', 'AppBootstrap'); logger.log('Switching logger', 'AppBootstrap');
app.useLogger(logger); app.useLogger(logger);
identityService = moduleRef.get(IdentityService);
const notesService: NotesService = moduleRef.get(NotesService); const notesService: NotesService = moduleRef.get(NotesService);
await notesService.createNote('test content', 'test_upload_media'); await notesService.createNote('test content', 'test_upload_media');
const userService: UsersService = moduleRef.get(UsersService); const userService: UsersService = moduleRef.get(UsersService);
await userService.createUser('hardcoded', 'Testy'); const user = await userService.createUser('hardcoded', 'Testy');
await identityService.createLocalIdentity(user, 'test');
agent = request.agent(app.getHttpServer());
await agent
.post('/auth/local/login')
.send({ username: 'hardcoded', password: 'test' })
.expect(201);
}); });
describe('POST /media', () => { describe('POST /media', () => {
it('works', async () => { it('works', async () => {
const uploadResponse = await request(app.getHttpServer()) const uploadResponse = await agent
.post('/media') .post('/media')
.attach('file', 'test/private-api/fixtures/test.png') .attach('file', 'test/private-api/fixtures/test.png')
.set('HedgeDoc-Note', 'test_upload_media') .set('HedgeDoc-Note', 'test_upload_media')
@ -87,7 +101,7 @@ describe('Media', () => {
.expect(201); .expect(201);
const path: string = uploadResponse.body.link; const path: string = uploadResponse.body.link;
const testImage = await fs.readFile('test/private-api/fixtures/test.png'); const testImage = await fs.readFile('test/private-api/fixtures/test.png');
const downloadResponse = await request(app.getHttpServer()).get(path); const downloadResponse = await agent.get(path);
expect(downloadResponse.body).toEqual(testImage); expect(downloadResponse.body).toEqual(testImage);
// Remove /uploads/ from path as we just need the filename. // Remove /uploads/ from path as we just need the filename.
const fileName = path.replace('/uploads/', ''); const fileName = path.replace('/uploads/', '');
@ -99,7 +113,7 @@ describe('Media', () => {
await ensureDeleted(uploadPath); await ensureDeleted(uploadPath);
}); });
it('MIME type not supported', async () => { it('MIME type not supported', async () => {
await request(app.getHttpServer()) await agent
.post('/media') .post('/media')
.attach('file', 'test/private-api/fixtures/test.zip') .attach('file', 'test/private-api/fixtures/test.zip')
.set('HedgeDoc-Note', 'test_upload_media') .set('HedgeDoc-Note', 'test_upload_media')
@ -107,7 +121,7 @@ describe('Media', () => {
await expect(fs.access(uploadPath)).rejects.toBeDefined(); await expect(fs.access(uploadPath)).rejects.toBeDefined();
}); });
it('note does not exist', async () => { it('note does not exist', async () => {
await request(app.getHttpServer()) await agent
.post('/media') .post('/media')
.attach('file', 'test/private-api/fixtures/test.zip') .attach('file', 'test/private-api/fixtures/test.zip')
.set('HedgeDoc-Note', 'i_dont_exist') .set('HedgeDoc-Note', 'i_dont_exist')
@ -118,7 +132,7 @@ describe('Media', () => {
await fs.mkdir(uploadPath, { await fs.mkdir(uploadPath, {
mode: '444', mode: '444',
}); });
await request(app.getHttpServer()) await agent
.post('/media') .post('/media')
.attach('file', 'test/private-api/fixtures/test.png') .attach('file', 'test/private-api/fixtures/test.png')
.set('HedgeDoc-Note', 'test_upload_media') .set('HedgeDoc-Note', 'test_upload_media')

View file

@ -13,6 +13,7 @@ import request from 'supertest';
import { PrivateApiModule } from '../../src/api/private/private-api.module'; import { PrivateApiModule } from '../../src/api/private/private-api.module';
import { AuthModule } from '../../src/auth/auth.module'; import { AuthModule } from '../../src/auth/auth.module';
import { AuthConfig } from '../../src/config/auth.config';
import appConfigMock from '../../src/config/mock/app.config.mock'; import appConfigMock from '../../src/config/mock/app.config.mock';
import authConfigMock from '../../src/config/mock/auth.config.mock'; import authConfigMock from '../../src/config/mock/auth.config.mock';
import customizationConfigMock from '../../src/config/mock/customization.config.mock'; import customizationConfigMock from '../../src/config/mock/customization.config.mock';
@ -20,6 +21,7 @@ import externalConfigMock from '../../src/config/mock/external-services.config.m
import mediaConfigMock from '../../src/config/mock/media.config.mock'; import mediaConfigMock from '../../src/config/mock/media.config.mock';
import { NotInDBError } from '../../src/errors/errors'; import { NotInDBError } from '../../src/errors/errors';
import { GroupsModule } from '../../src/groups/groups.module'; import { GroupsModule } from '../../src/groups/groups.module';
import { IdentityService } from '../../src/identity/identity.service';
import { LoggerModule } from '../../src/logger/logger.module'; import { LoggerModule } from '../../src/logger/logger.module';
import { MediaService } from '../../src/media/media.service'; import { MediaService } from '../../src/media/media.service';
import { NotesModule } from '../../src/notes/notes.module'; import { NotesModule } from '../../src/notes/notes.module';
@ -28,17 +30,20 @@ import { PermissionsModule } from '../../src/permissions/permissions.module';
import { User } from '../../src/users/user.entity'; import { User } from '../../src/users/user.entity';
import { UsersModule } from '../../src/users/users.module'; import { UsersModule } from '../../src/users/users.module';
import { UsersService } from '../../src/users/users.service'; import { UsersService } from '../../src/users/users.service';
import { setupSessionMiddleware } from '../../src/utils/session';
describe('Notes', () => { describe('Notes', () => {
let app: INestApplication; let app: INestApplication;
let notesService: NotesService; let notesService: NotesService;
let mediaService: MediaService; let mediaService: MediaService;
let identityService: IdentityService;
let user: User; let user: User;
let user2: User; let user2: User;
let content: string; let content: string;
let forbiddenNoteId: string; let forbiddenNoteId: string;
let uploadPath: string; let uploadPath: string;
let testImage: Buffer; let testImage: Buffer;
let agent: request.SuperAgentTest;
beforeAll(async () => { beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ const moduleRef = await Test.createTestingModule({
@ -74,18 +79,28 @@ describe('Notes', () => {
forbiddenNoteId = config.get('appConfig').forbiddenNoteIds[0]; forbiddenNoteId = config.get('appConfig').forbiddenNoteIds[0];
uploadPath = config.get('mediaConfig').backend.filesystem.uploadPath; uploadPath = config.get('mediaConfig').backend.filesystem.uploadPath;
app = moduleRef.createNestApplication(); app = moduleRef.createNestApplication();
const authConfig = config.get('authConfig') as AuthConfig;
setupSessionMiddleware(app, authConfig);
await app.init(); await app.init();
notesService = moduleRef.get(NotesService); notesService = moduleRef.get(NotesService);
mediaService = moduleRef.get(MediaService); mediaService = moduleRef.get(MediaService);
identityService = moduleRef.get(IdentityService);
const userService = moduleRef.get(UsersService); const userService = moduleRef.get(UsersService);
user = await userService.createUser('hardcoded', 'Testy'); user = await userService.createUser('hardcoded', 'Testy');
await identityService.createLocalIdentity(user, 'test');
user2 = await userService.createUser('hardcoded2', 'Max Mustermann'); user2 = await userService.createUser('hardcoded2', 'Max Mustermann');
await identityService.createLocalIdentity(user2, 'test');
content = 'This is a test note.'; content = 'This is a test note.';
testImage = await fs.readFile('test/public-api/fixtures/test.png'); testImage = await fs.readFile('test/public-api/fixtures/test.png');
agent = request.agent(app.getHttpServer());
await agent
.post('/auth/local/login')
.send({ username: 'hardcoded', password: 'test' })
.expect(201);
}); });
it('POST /notes', async () => { it('POST /notes', async () => {
const response = await request(app.getHttpServer()) const response = await agent
.post('/notes') .post('/notes')
.set('Content-Type', 'text/markdown') .set('Content-Type', 'text/markdown')
.send(content) .send(content)
@ -103,7 +118,7 @@ describe('Notes', () => {
it('works with an existing note', async () => { it('works with an existing note', async () => {
// check if we can succefully get a note that exists // check if we can succefully get a note that exists
await notesService.createNote(content, 'test1', user); await notesService.createNote(content, 'test1', user);
const response = await request(app.getHttpServer()) const response = await agent
.get('/notes/test1') .get('/notes/test1')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
@ -111,7 +126,7 @@ describe('Notes', () => {
}); });
it('fails with an non-existing note', async () => { it('fails with an non-existing note', async () => {
// check if a missing note correctly returns 404 // check if a missing note correctly returns 404
await request(app.getHttpServer()) await agent
.get('/notes/i_dont_exist') .get('/notes/i_dont_exist')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(404); .expect(404);
@ -120,7 +135,7 @@ describe('Notes', () => {
describe('POST /notes/{note}', () => { describe('POST /notes/{note}', () => {
it('works with a non-existing alias', async () => { it('works with a non-existing alias', async () => {
const response = await request(app.getHttpServer()) const response = await agent
.post('/notes/test2') .post('/notes/test2')
.set('Content-Type', 'text/markdown') .set('Content-Type', 'text/markdown')
.send(content) .send(content)
@ -135,7 +150,7 @@ describe('Notes', () => {
}); });
it('fails with a forbidden alias', async () => { it('fails with a forbidden alias', async () => {
await request(app.getHttpServer()) await agent
.post(`/notes/${forbiddenNoteId}`) .post(`/notes/${forbiddenNoteId}`)
.set('Content-Type', 'text/markdown') .set('Content-Type', 'text/markdown')
.send(content) .send(content)
@ -144,7 +159,7 @@ describe('Notes', () => {
}); });
it('fails with a existing alias', async () => { it('fails with a existing alias', async () => {
await request(app.getHttpServer()) await agent
.post('/notes/test2') .post('/notes/test2')
.set('Content-Type', 'text/markdown') .set('Content-Type', 'text/markdown')
.send(content) .send(content)
@ -159,7 +174,7 @@ describe('Notes', () => {
const noteId = 'test3'; const noteId = 'test3';
const note = await notesService.createNote(content, noteId, user); const note = await notesService.createNote(content, noteId, user);
await mediaService.saveFile(testImage, user, note); await mediaService.saveFile(testImage, user, note);
await request(app.getHttpServer()) await agent
.delete(`/notes/${noteId}`) .delete(`/notes/${noteId}`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send({ .send({
@ -176,7 +191,7 @@ describe('Notes', () => {
const noteId = 'test3a'; const noteId = 'test3a';
const note = await notesService.createNote(content, noteId, user); const note = await notesService.createNote(content, noteId, user);
const url = await mediaService.saveFile(testImage, user, note); const url = await mediaService.saveFile(testImage, user, note);
await request(app.getHttpServer()) await agent
.delete(`/notes/${noteId}`) .delete(`/notes/${noteId}`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.send({ .send({
@ -195,21 +210,17 @@ describe('Notes', () => {
}); });
}); });
it('fails with a forbidden alias', async () => { it('fails with a forbidden alias', async () => {
await request(app.getHttpServer()) await agent.delete(`/notes/${forbiddenNoteId}`).expect(400);
.delete(`/notes/${forbiddenNoteId}`)
.expect(400);
}); });
it('fails with a non-existing alias', async () => { it('fails with a non-existing alias', async () => {
await request(app.getHttpServer()) await agent.delete('/notes/i_dont_exist').expect(404);
.delete('/notes/i_dont_exist')
.expect(404);
}); });
}); });
describe('GET /notes/{note}/revisions', () => { describe('GET /notes/{note}/revisions', () => {
it('works with existing alias', async () => { it('works with existing alias', async () => {
await notesService.createNote(content, 'test4', user); await notesService.createNote(content, 'test4', user);
const response = await request(app.getHttpServer()) const response = await agent
.get('/notes/test4/revisions') .get('/notes/test4/revisions')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
@ -217,14 +228,12 @@ describe('Notes', () => {
}); });
it('fails with a forbidden alias', async () => { it('fails with a forbidden alias', async () => {
await request(app.getHttpServer()) await agent.get(`/notes/${forbiddenNoteId}/revisions`).expect(400);
.get(`/notes/${forbiddenNoteId}/revisions`)
.expect(400);
}); });
it('fails with non-existing alias', async () => { it('fails with non-existing alias', async () => {
// check if a missing note correctly returns 404 // check if a missing note correctly returns 404
await request(app.getHttpServer()) await agent
.get('/notes/i_dont_exist/revisions') .get('/notes/i_dont_exist/revisions')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(404); .expect(404);
@ -236,29 +245,27 @@ describe('Notes', () => {
const noteId = 'test8'; const noteId = 'test8';
const note = await notesService.createNote(content, noteId, user); const note = await notesService.createNote(content, noteId, user);
await notesService.updateNote(note, 'update'); await notesService.updateNote(note, 'update');
const responseBeforeDeleting = await request(app.getHttpServer()) const responseBeforeDeleting = await agent
.get('/notes/test8/revisions') .get('/notes/test8/revisions')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
expect(responseBeforeDeleting.body).toHaveLength(2); expect(responseBeforeDeleting.body).toHaveLength(2);
await request(app.getHttpServer()) await agent
.delete(`/notes/${noteId}/revisions`) .delete(`/notes/${noteId}/revisions`)
.set('Content-Type', 'application/json') .set('Content-Type', 'application/json')
.expect(204); .expect(204);
const responseAfterDeleting = await request(app.getHttpServer()) const responseAfterDeleting = await agent
.get('/notes/test8/revisions') .get('/notes/test8/revisions')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
expect(responseAfterDeleting.body).toHaveLength(1); expect(responseAfterDeleting.body).toHaveLength(1);
}); });
it('fails with a forbidden alias', async () => { it('fails with a forbidden alias', async () => {
await request(app.getHttpServer()) await agent.delete(`/notes/${forbiddenNoteId}/revisions`).expect(400);
.delete(`/notes/${forbiddenNoteId}/revisions`)
.expect(400);
}); });
it('fails with non-existing alias', async () => { it('fails with non-existing alias', async () => {
// check if a missing note correctly returns 404 // check if a missing note correctly returns 404
await request(app.getHttpServer()) await agent
.delete('/notes/i_dont_exist/revisions') .delete('/notes/i_dont_exist/revisions')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(404); .expect(404);
@ -269,20 +276,18 @@ describe('Notes', () => {
it('works with an existing alias', async () => { it('works with an existing alias', async () => {
const note = await notesService.createNote(content, 'test5', user); const note = await notesService.createNote(content, 'test5', user);
const revision = await notesService.getLatestRevision(note); const revision = await notesService.getLatestRevision(note);
const response = await request(app.getHttpServer()) const response = await agent
.get(`/notes/test5/revisions/${revision.id}`) .get(`/notes/test5/revisions/${revision.id}`)
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
expect(response.body.content).toEqual(content); expect(response.body.content).toEqual(content);
}); });
it('fails with a forbidden alias', async () => { it('fails with a forbidden alias', async () => {
await request(app.getHttpServer()) await agent.get(`/notes/${forbiddenNoteId}/revisions/1`).expect(400);
.get(`/notes/${forbiddenNoteId}/revisions/1`)
.expect(400);
}); });
it('fails with non-existing alias', async () => { it('fails with non-existing alias', async () => {
// check if a missing note correctly returns 404 // check if a missing note correctly returns 404
await request(app.getHttpServer()) await agent
.get('/notes/i_dont_exist/revisions/1') .get('/notes/i_dont_exist/revisions/1')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(404); .expect(404);
@ -295,8 +300,7 @@ describe('Notes', () => {
const extraAlias = 'test7'; const extraAlias = 'test7';
const note1 = await notesService.createNote(content, alias, user); const note1 = await notesService.createNote(content, alias, user);
const note2 = await notesService.createNote(content, extraAlias, user); const note2 = await notesService.createNote(content, extraAlias, user);
const httpServer = app.getHttpServer(); const response = await agent
const response = await request(httpServer)
.get(`/notes/${alias}/media/`) .get(`/notes/${alias}/media/`)
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
@ -306,7 +310,7 @@ describe('Notes', () => {
const url0 = await mediaService.saveFile(testImage, user, note1); const url0 = await mediaService.saveFile(testImage, user, note1);
const url1 = await mediaService.saveFile(testImage, user, note2); const url1 = await mediaService.saveFile(testImage, user, note2);
const responseAfter = await request(httpServer) const responseAfter = await agent
.get(`/notes/${alias}/media/`) .get(`/notes/${alias}/media/`)
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200); .expect(200);
@ -321,7 +325,7 @@ describe('Notes', () => {
await fs.rmdir(uploadPath, { recursive: true }); await fs.rmdir(uploadPath, { recursive: true });
}); });
it('fails, when note does not exist', async () => { it('fails, when note does not exist', async () => {
await request(app.getHttpServer()) await agent
.get(`/notes/i_dont_exist/media/`) .get(`/notes/i_dont_exist/media/`)
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(404); .expect(404);
@ -329,7 +333,7 @@ describe('Notes', () => {
it("fails, when user can't read note", async () => { it("fails, when user can't read note", async () => {
const alias = 'test11'; const alias = 'test11';
await notesService.createNote('This is a test note.', alias, user2); await notesService.createNote('This is a test note.', alias, user2);
await request(app.getHttpServer()) await agent
.get(`/notes/${alias}/media/`) .get(`/notes/${alias}/media/`)
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(401); .expect(401);