159 lines
5.3 KiB
TypeScript
159 lines
5.3 KiB
TypeScript
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { APP_GUARD } from '@nestjs/core';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { PassportModule } from '@nestjs/passport';
|
|
import { Test } from '@nestjs/testing';
|
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
|
import { mkdtemp, readdir, rmdir, unlink } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import request from 'supertest';
|
|
import type { App } from 'supertest/types';
|
|
import { Role } from '@/common/enums/roles.enum';
|
|
import { ResponseInterceptor } from '@/common/interceptors/response.interceptor';
|
|
import jwtConfig from '@/config/jwt.config';
|
|
import { AuthRedisProvider } from '@/modules/auth/providers/auth-redis.provider';
|
|
import { GlobalAuthGuard } from '@/modules/auth/guards/global-auth.guard';
|
|
import { JwtStrategy } from '@/modules/auth/strategies/jwt.strategy';
|
|
import { ArticleIngestion } from '@/modules/rag/article-ingestion.service';
|
|
import { ArticlesController } from '@/modules/rag/articles.controller';
|
|
import { Article } from '@/modules/rag/entities/article.entity';
|
|
import { UsersService } from '@/modules/users/providers/users.service';
|
|
|
|
describe('Article upload HTTP API', () => {
|
|
let app: INestApplication<App>;
|
|
let storage: string;
|
|
const records = new Map<string, Article>();
|
|
const kick = jest.fn();
|
|
const secret = 'local-test-secret';
|
|
const issuer = 'test';
|
|
const audience = 'test';
|
|
const auth = new JwtService({
|
|
secret,
|
|
signOptions: { issuer, audience, expiresIn: 300 },
|
|
});
|
|
|
|
beforeAll(async () => {
|
|
storage = await mkdtemp(join(tmpdir(), 'heala-rag-'));
|
|
const module = await Test.createTestingModule({
|
|
imports: [PassportModule],
|
|
controllers: [ArticlesController],
|
|
providers: [
|
|
JwtStrategy,
|
|
{ provide: APP_GUARD, useClass: GlobalAuthGuard },
|
|
{
|
|
provide: jwtConfig.KEY,
|
|
useValue: { access: { secret }, issuer, audience },
|
|
},
|
|
{
|
|
provide: AuthRedisProvider,
|
|
useValue: { isAccessTokenBlacklisted: () => false },
|
|
},
|
|
{
|
|
provide: UsersService,
|
|
useValue: {
|
|
findOneByPhone: (phone: string) => ({
|
|
role: phone === 'admin' ? Role.ADMIN : Role.USER,
|
|
}),
|
|
},
|
|
},
|
|
{ provide: ArticleIngestion, useValue: { kick } },
|
|
{
|
|
provide: ConfigService,
|
|
useValue: new ConfigService({
|
|
RAG_ENABLED: true,
|
|
RAG_STORAGE_DIR: storage,
|
|
RAG_UPLOAD_MIME_TYPES: 'text/plain',
|
|
RAG_UPLOAD_MAX_BYTES: 1000,
|
|
}),
|
|
},
|
|
{
|
|
provide: getRepositoryToken(Article),
|
|
useValue: {
|
|
save: (article: Article) => {
|
|
records.set(article.id, article);
|
|
return article;
|
|
},
|
|
findOneBy: ({ id }: { id: string }) => records.get(id) ?? null,
|
|
},
|
|
},
|
|
],
|
|
}).compile();
|
|
|
|
app = module.createNestApplication();
|
|
app.setGlobalPrefix('v1');
|
|
app.useGlobalPipes(
|
|
new ValidationPipe({
|
|
whitelist: true,
|
|
forbidNonWhitelisted: true,
|
|
transform: true,
|
|
}),
|
|
);
|
|
app.useGlobalInterceptors(new ResponseInterceptor());
|
|
await app.init();
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await app?.close();
|
|
if (storage) {
|
|
for (const name of await readdir(storage))
|
|
await unlink(join(storage, name));
|
|
await rmdir(storage);
|
|
}
|
|
});
|
|
|
|
const token = (phone: string) =>
|
|
`Bearer ${auth.sign({ phone, jti: 'test-token' })}`;
|
|
|
|
it('requires an authenticated administrator', async () => {
|
|
await request(app.getHttpServer()).post('/v1/articles').expect(401);
|
|
await request(app.getHttpServer())
|
|
.post('/v1/articles')
|
|
.set('Authorization', token('user'))
|
|
.expect(403);
|
|
});
|
|
|
|
it('queues valid multipart files and returns pending status through the application envelope', async () => {
|
|
const upload = await request(app.getHttpServer())
|
|
.post('/v1/articles')
|
|
.set('Authorization', token('admin'))
|
|
.field('title', 'Medical education article')
|
|
.attach('file', Buffer.from('Educational text'), {
|
|
filename: 'article.txt',
|
|
contentType: 'text/plain',
|
|
})
|
|
.expect(202);
|
|
const { data } = upload.body as {
|
|
data: {
|
|
id: string;
|
|
status: string;
|
|
fileName: string;
|
|
storageKey?: string;
|
|
};
|
|
};
|
|
expect(data).toMatchObject({ status: 'pending', fileName: 'article.txt' });
|
|
expect(data.storageKey).toBeUndefined();
|
|
expect(await readdir(storage)).toEqual([records.get(data.id)?.storageKey]);
|
|
expect(kick).toHaveBeenCalledTimes(1);
|
|
await request(app.getHttpServer())
|
|
.get(`/v1/articles/${data.id}`)
|
|
.set('Authorization', token('admin'))
|
|
.expect(200);
|
|
});
|
|
|
|
it('rejects a malformed UTF-8 document and an oversize file', async () => {
|
|
for (const content of [Buffer.from([0xff]), Buffer.alloc(1001, 'a')]) {
|
|
await request(app.getHttpServer())
|
|
.post('/v1/articles')
|
|
.set('Authorization', token('admin'))
|
|
.field('title', 'Invalid')
|
|
.attach('file', content, {
|
|
filename: 'article.txt',
|
|
contentType: 'text/plain',
|
|
})
|
|
.expect(400);
|
|
}
|
|
});
|
|
});
|