Не подтверждена Коммит 1aec1ce7 создал по автору LongYinan's avatar LongYinan Зафиксировано автором GitHub
Просмотр файлов

test(server): move tests out of src folder (#4366)

владелец b5e8fecf
......@@ -272,6 +272,7 @@ const config = {
],
'@typescript-eslint/no-floating-promises': 0,
'@typescript-eslint/no-misused-promises': 0,
'@typescript-eslint/no-restricted-imports': 0,
},
},
],
......
......@@ -118,7 +118,7 @@ jobs:
CARGO_TARGET_DIR: '${{ github.workspace }}/target'
DATABASE_URL: postgresql://affine:affine@localhost:5432/affine
ENABLE_LOCAL_EMAIL: true
OAUTH_EMAIL_LOGIN: affine
OAUTH_EMAIL_LOGIN: noreply@toeverything.info
OAUTH_EMAIL_PASSWORD: affine
- name: Upload server test coverage results
......@@ -191,9 +191,6 @@ jobs:
env:
COVERAGE: true
DATABASE_URL: postgresql://affine:affine@localhost:5432/affine
ENABLE_LOCAL_EMAIL: true
OAUTH_EMAIL_LOGIN: affine
OAUTH_EMAIL_PASSWORD: affine
- name: Collect code coverage report
run: yarn exec nyc report -t .nyc_output --report-dir .coverage --reporter=lcov
......
......@@ -44,7 +44,6 @@ export const UserAvatar = () => {
const handleUpdateUserAvatar = useCallback(
async (file: File) => {
await avatarTrigger({
id: user.id,
avatar: file,
});
// XXX: This is a hack to force the user to update, since next-auth can not only use update function without params
......
......@@ -81,6 +81,7 @@
"@types/cookie-parser": "^1.4.3",
"@types/engine.io": "^3.1.7",
"@types/express": "^4.17.17",
"@types/graphql-upload": "^16.0.1",
"@types/keyv": "^4.2.0",
"@types/lodash-es": "^4.17.9",
"@types/node": "^18.17.12",
......@@ -104,19 +105,24 @@
},
"nodeArguments": [
"--loader",
"ts-node/esm.mjs",
"ts-node/esm/transpile-only.mjs",
"--es-module-specifier-resolution",
"node"
],
"files": [
"src/**/*.spec.ts"
"tests/**/*.spec.ts",
"tests/**/*.e2e.ts"
],
"require": [
"./src/prelude.ts"
],
"environmentVariables": {
"TS_NODE_PROJECT": "./tsconfig.json",
"NODE_ENV": "test"
"TS_NODE_PROJECT": "./tests/tsconfig.json",
"NODE_ENV": "test",
"ENABLE_LOCAL_EMAIL": "true",
"OAUTH_EMAIL_LOGIN": "noreply@toeverything.info",
"OAUTH_EMAIL_PASSWORD": "affine",
"OAUTH_EMAIL_SENDER": "noreply@toeverything.info"
}
},
"nodemonConfig": {
......
......@@ -19,7 +19,6 @@ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-node';
import { PrismaInstrumentation } from '@prisma/instrumentation';
import cookieParser from 'cookie-parser';
import { static as staticMiddleware } from 'express';
// @ts-expect-error graphql-upload is not typed
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
import { AppModule } from './app';
......
......@@ -16,8 +16,7 @@ import { NextAuthOptionsProvide } from './next-auth-options';
import { AuthService } from './service';
export function getUserFromContext(context: ExecutionContext) {
const req = getRequestResponseFromContext(context).req;
return req.user;
return getRequestResponseFromContext(context).req.user;
}
/**
......
......@@ -15,7 +15,6 @@ import {
Resolver,
} from '@nestjs/graphql';
import type { User } from '@prisma/client';
// @ts-expect-error graphql-upload is not typed
import GraphQLUpload from 'graphql-upload/GraphQLUpload.mjs';
import { PrismaService } from '../../prisma/service';
......@@ -141,17 +140,16 @@ export class UserResolver {
description: 'Upload user avatar',
})
async uploadAvatar(
@Args('id') id: string,
@CurrentUser() user: UserType,
@Args({ name: 'avatar', type: () => GraphQLUpload })
avatar: FileUpload
) {
const user = await this.users.findUserById(id);
if (!user) {
throw new BadRequestException(`User ${id} not found`);
throw new BadRequestException(`User not found`);
}
const url = await this.storage.uploadFile(`${id}-avatar`, avatar);
const url = await this.storage.uploadFile(`${user.id}-avatar`, avatar);
return this.prisma.user.update({
where: { id },
where: { id: user.id },
data: { avatarUrl: url },
});
}
......
......@@ -26,7 +26,6 @@ import {
Resolver,
} from '@nestjs/graphql';
import type { User, Workspace } from '@prisma/client';
// @ts-expect-error graphql-upload is not typed
import GraphQLUpload from 'graphql-upload/GraphQLUpload.mjs';
import { applyUpdate, Doc } from 'yjs';
......@@ -648,10 +647,10 @@ export class WorkspaceResolver {
workspaceId,
},
});
return (
userWorkspace?.accepted &&
(await this.permissions.grantPage(workspaceId, pageId))
);
if (!userWorkspace?.accepted) {
throw new ForbiddenException('Permission denied');
}
return this.permissions.grantPage(workspaceId, pageId);
}
@Mutation(() => Boolean)
......
......@@ -190,7 +190,7 @@ type Mutation {
deleteBlob(workspaceId: String!, hash: String!): Boolean!
"""Upload user avatar"""
uploadAvatar(id: String!, avatar: Upload!): UserType!
uploadAvatar(avatar: Upload!): UserType!
"""Remove user avatar"""
removeAvatar: RemoveAvatar!
......
......@@ -8,12 +8,11 @@ import { hashSync } from '@node-rs/argon2';
import { User } from '@prisma/client';
import ava, { TestFn } from 'ava';
import { Express } from 'express';
// @ts-expect-error graphql-upload is not typed
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
import request from 'supertest';
import { AppModule } from '../app';
import { PrismaService } from '../prisma/service';
import { AppModule } from '../src/app';
import { PrismaService } from '../src/prisma/service';
const gql = '/graphql';
......@@ -139,8 +138,8 @@ test('should be able to upload avatar and remove it', async t => {
'operations',
JSON.stringify({
name: 'uploadAvatar',
query: `mutation uploadAvatar($id: String!, $avatar: Upload!) {
uploadAvatar(id: $id, avatar: $avatar) {
query: `mutation uploadAvatar($avatar: Upload!) {
uploadAvatar(avatar: $avatar) {
id
name
avatarUrl
......@@ -166,17 +165,14 @@ test('should be able to upload avatar and remove it', async t => {
query: `
mutation removeAvatar {
removeAvatar {
id
name
avatarUrl
email
success
}
}
`,
})
.expect(200)
.expect(res => {
t.is(res.body.data.removeAvatar.avatarUrl, '');
t.is(res.body.data.removeAvatar.success, true);
});
});
......
import {
getCurrentMailMessageCount,
getLatestMailMessage,
} from '@affine-test/kit/utils/cloud';
import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { PrismaClient } from '@prisma/client';
import ava, { TestFn } from 'ava';
// @ts-expect-error graphql-upload is not typed
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
import { AppModule } from '../app';
import { MailService } from '../modules/auth/mailer';
import { AuthService } from '../modules/auth/service';
import { AppModule } from '../src/app';
import { MailService } from '../src/modules/auth/mailer';
import { AuthService } from '../src/modules/auth/service';
import {
changeEmail,
createWorkspace,
getCurrentMailMessageCount,
getLatestMailMessage,
sendChangeEmail,
sendVerifyChangeEmail,
signUp,
......
/// <reference types="../global.d.ts" />
/// <reference types="../src/global.d.ts" />
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaClient } from '@prisma/client';
import test from 'ava';
import { ConfigModule } from '../config';
import { GqlModule } from '../graphql.module';
import { MetricsModule } from '../metrics';
import { AuthModule } from '../modules/auth';
import { AuthResolver } from '../modules/auth/resolver';
import { AuthService } from '../modules/auth/service';
import { PrismaModule } from '../prisma';
import { RateLimiterModule } from '../throttler';
import { ConfigModule } from '../src/config';
import { GqlModule } from '../src/graphql.module';
import { MetricsModule } from '../src/metrics';
import { AuthModule } from '../src/modules/auth';
import { AuthResolver } from '../src/modules/auth/resolver';
import { AuthService } from '../src/modules/auth/service';
import { PrismaModule } from '../src/prisma';
import { RateLimiterModule } from '../src/throttler';
let authService: AuthService;
let authResolver: AuthResolver;
......
import { Test, TestingModule } from '@nestjs/testing';
import test from 'ava';
import { Config, ConfigModule } from '../config';
import { Config, ConfigModule } from '../src/config';
let config: Config;
let module: TestingModule;
......
......@@ -7,10 +7,10 @@ import { register } from 'prom-client';
import * as Sinon from 'sinon';
import { Doc as YDoc, encodeStateAsUpdate } from 'yjs';
import { Config, ConfigModule } from '../config';
import { MetricsModule } from '../metrics';
import { DocManager, DocModule } from '../modules/doc';
import { PrismaModule, PrismaService } from '../prisma';
import { Config, ConfigModule } from '../src/config';
import { MetricsModule } from '../src/metrics';
import { DocManager, DocModule } from '../src/modules/doc';
import { PrismaModule, PrismaService } from '../src/prisma';
import { flushDB } from './utils';
const createModule = () => {
......
import { Controller, Get, INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import test from 'ava';
// @ts-expect-error graphql-upload is not typed
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
import request from 'supertest';
import { AppModule } from '../app';
import { ExceptionLogger } from '../middleware/exception-logger';
import { PrismaService } from '../prisma';
import { AppModule } from '../src/app';
import { ExceptionLogger } from '../src/middleware/exception-logger';
import { PrismaService } from '../src/prisma';
const gql = '/graphql';
const rest = '/rest';
......
/// <reference types="../global.d.ts" />
/// <reference types="../src/global.d.ts" />
// This test case is for testing the mailer service.
// Please use local SMTP server for testing.
// See: https://github.com/mailhog/MailHog
......@@ -8,38 +8,21 @@ import {
} from '@affine-test/kit/utils/cloud';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaClient } from '@prisma/client';
import test from 'ava';
import ava, { TestFn } from 'ava';
import { ConfigModule } from '../config';
import { GqlModule } from '../graphql.module';
import { MetricsModule } from '../metrics';
import { AuthModule } from '../modules/auth';
import { AuthService } from '../modules/auth/service';
import { PrismaModule } from '../prisma';
import { RateLimiterModule } from '../throttler';
import { ConfigModule } from '../src/config';
import { GqlModule } from '../src/graphql.module';
import { MetricsModule } from '../src/metrics';
import { AuthModule } from '../src/modules/auth';
import { AuthService } from '../src/modules/auth/service';
import { PrismaModule } from '../src/prisma';
import { RateLimiterModule } from '../src/throttler';
let auth: AuthService;
let module: TestingModule;
let skip = false;
test.before(async () => {
try {
const response = await fetch('http://localhost:8025/api/v2/messages');
if (!response.ok && !process.env.CI) {
console.warn('local mail not found, skip the mailer.e2e.ts');
skip = true;
}
} catch (error) {
if (
error instanceof Error &&
(error.cause as any)?.code === 'ECONNREFUSED' &&
!process.env.CI
) {
console.warn('local mail not found, skip the mailer.e2e.ts');
skip = true;
}
}
});
const test = ava as TestFn<{
auth: AuthService;
module: TestingModule;
skip: boolean;
}>;
// cleanup database before each test
test.beforeEach(async () => {
......@@ -48,8 +31,8 @@ test.beforeEach(async () => {
await client.user.deleteMany({});
});
test.beforeEach(async () => {
module = await Test.createTestingModule({
test.beforeEach(async t => {
t.context.module = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
auth: {
......@@ -65,18 +48,16 @@ test.beforeEach(async () => {
RateLimiterModule,
],
}).compile();
auth = module.get(AuthService);
t.context.auth = t.context.module.get(AuthService);
});
test.afterEach.always(async () => {
await module.close();
test.afterEach.always(async t => {
await t.context.module.close();
});
test('should include callbackUrl in sending email', async t => {
if (skip) {
return t.pass();
}
// await auth.signUp('Alex Yang', 'alexyang@example.org', '123456');
const { auth } = t.context;
await auth.signUp('Alex Yang', 'alexyang@example.org', '123456');
for (const fn of [
'sendSetPasswordEmail',
'sendChangeEmail',
......@@ -88,11 +69,10 @@ test('should include callbackUrl in sending email', async t => {
const current = await getCurrentMailMessageCount();
const mail = await getLatestMailMessage();
t.regex(
mail.Content.Body,
mail?.Content?.Body,
/https:\/\/test.com\/callback/,
`should include callbackUrl when calling ${fn}`
);
t.is(current, prev + 1, `calling ${fn}`);
}
return;
});
import { ok } from 'node:assert';
import { randomUUID } from 'node:crypto';
import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { hashSync } from '@node-rs/argon2';
import { User } from '@prisma/client';
import test from 'ava';
// @ts-expect-error graphql-upload is not typed
import ava, { TestFn } from 'ava';
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
import { AppModule } from '../app';
import { MailService } from '../modules/auth/mailer';
import { PrismaService } from '../prisma';
import { AppModule } from '../src/app';
import { MailService } from '../src/modules/auth/mailer';
import { PrismaService } from '../src/prisma';
import { createWorkspace, getInviteInfo, inviteUser, signUp } from './utils';
let app: INestApplication;
let mail: MailService;
const FakePrisma = {
fakeUser: {
id: randomUUID(),
......@@ -95,14 +89,19 @@ const FakePrisma = {
},
};
test.beforeEach(async () => {
const test = ava as TestFn<{
app: INestApplication;
mail: MailService;
}>;
test.beforeEach(async t => {
const module = await Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider(PrismaService)
.useValue(FakePrisma)
.compile();
app = module.createNestApplication();
const app = module.createNestApplication();
app.use(
graphqlUploadExpress({
maxFileSize: 10 * 1024 * 1024,
......@@ -111,14 +110,17 @@ test.beforeEach(async () => {
);
await app.init();
mail = module.get(MailService);
const mail = module.get(MailService);
t.context.app = app;
t.context.mail = mail;
});
test.afterEach.always(async () => {
await app.close();
test.afterEach.always(async t => {
await t.context.app.close();
});
test('should send invite email', async t => {
const { mail, app } = t.context;
if (mail.hasConfigured()) {
const u1 = await signUp(app, 'u1', 'u1@affine.pro', '1');
const u2 = await signUp(app, 'u2', 'u2@affine.pro', '1');
......@@ -150,7 +152,7 @@ test('should send invite email', async t => {
}
);
ok(resp.accepted.length === 1, 'failed to send invite email');
t.is(resp.accepted.length, 1, 'failed to send invite email');
}
t.pass();
});
......@@ -2,9 +2,9 @@ import { Test, TestingModule } from '@nestjs/testing';
import test from 'ava';
import { register } from 'prom-client';
import { MetricsModule } from '../metrics';
import { Metrics } from '../metrics/metrics';
import { PrismaModule } from '../prisma';
import { MetricsModule } from '../src/metrics';
import { Metrics } from '../src/metrics/metrics';
import { PrismaModule } from '../src/prisma';
let metrics: Metrics;
let module: TestingModule;
......
/// <reference types="../global.d.ts" />
/// <reference types="../src/global.d.ts" />
import { Test, TestingModule } from '@nestjs/testing';
import ava, { TestFn } from 'ava';
import { ConfigModule } from '../config';
import { SessionModule, SessionService } from '../session';
import { ConfigModule } from '../src/config';
import { SessionModule, SessionService } from '../src/session';
const test = ava as TestFn<{
session: SessionService;
......
{
"extends": "../tsconfig.json",
"compilerOptions": {
"composite": true,
"target": "ESNext",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"rootDir": ".",
"outDir": "../dist/tests"
},
"references": [
{
"path": "../tsconfig.json"
},
{
"path": "../../../tests/kit/tsconfig.json"
}
],
"include": ["."],
"exclude": []
}
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать