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

This commit is contained in:
LongYinan
2023-09-15 00:34:14 -07:00
committed by GitHub
parent b5e8fecfd0
commit 1aec1ce7d0
36 changed files with 233 additions and 159 deletions

View File

@@ -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": {

View File

@@ -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';

View File

@@ -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;
}
/**

View File

@@ -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 },
});
}

View File

@@ -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)

View File

@@ -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!

View File

@@ -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);
});
});

View File

@@ -1,18 +1,19 @@
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,

View File

@@ -1,16 +1,16 @@
/// <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;

View File

@@ -1,7 +1,7 @@
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;

View File

@@ -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 = () => {

View File

@@ -1,13 +1,12 @@
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';

View File

@@ -1,4 +1,4 @@
/// <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;
});

View File

@@ -1,23 +1,17 @@
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();
});

View File

@@ -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;

View File

@@ -1,10 +1,10 @@
/// <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;

View File

@@ -0,0 +1,21 @@
{
"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": []
}

View File

@@ -2,11 +2,10 @@ import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { PrismaClient } from '@prisma/client';
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 { AppModule } from '../src/app';
import { currentUser, signUp } from './utils';
let app: INestApplication;

View File

@@ -5,9 +5,9 @@ import { hashSync } from '@node-rs/argon2';
import { PrismaClient, User } from '@prisma/client';
import request from 'supertest';
import type { TokenType } from '../modules/auth';
import type { UserType } from '../modules/users';
import type { InvitationType, WorkspaceType } from '../modules/workspaces';
import type { TokenType } from '../src/modules/auth';
import type { UserType } from '../src/modules/users';
import type { InvitationType, WorkspaceType } from '../src/modules/workspaces';
const gql = '/graphql';

View File

@@ -2,11 +2,10 @@ import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { PrismaClient } from '@prisma/client';
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 { AppModule } from '../src/app';
import {
checkBlobSize,
collectAllBlobSizes,

View File

@@ -6,12 +6,11 @@ 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 {
acceptInvite,
acceptInviteById,
@@ -202,8 +201,7 @@ test('should send email', async t => {
const inviteEmailContent = await getLatestMailMessage();
t.not(
// @ts-expect-error Third part library type mismatch
inviteEmailContent.To.find(item => {
inviteEmailContent.To.find((item: any) => {
return item.Mailbox === 'production';
}),
undefined,
@@ -221,8 +219,7 @@ test('should send email', async t => {
);
const acceptEmailContent = await getLatestMailMessage();
t.not(
// @ts-expect-error Third part library type mismatch
acceptEmailContent.To.find(item => {
acceptEmailContent.To.find((item: any) => {
return item.Mailbox === 'u1';
}),
undefined,
@@ -239,8 +236,7 @@ test('should send email', async t => {
);
const leaveEmailContent = await getLatestMailMessage();
t.not(
// @ts-expect-error Third part library type mismatch
leaveEmailContent.To.find(item => {
leaveEmailContent.To.find((item: any) => {
return item.Mailbox === 'u1';
}),
undefined,

View File

@@ -3,12 +3,12 @@ import { Test } from '@nestjs/testing';
import ava, { TestFn } from 'ava';
import { stub } from 'sinon';
import { AppModule } from '../app';
import { UsersService } from '../modules/users';
import { PermissionService } from '../modules/workspaces/permission';
import { WorkspaceResolver } from '../modules/workspaces/resolver';
import { PrismaService } from '../prisma';
import { StorageProvide } from '../storage';
import { AppModule } from '../src/app';
import { UsersService } from '../src/modules/users';
import { PermissionService } from '../src/modules/workspaces/permission';
import { WorkspaceResolver } from '../src/modules/workspaces/resolver';
import { PrismaService } from '../src/prisma';
import { StorageProvide } from '../src/storage';
import { FakePrisma } from './utils';
class FakePermission {

View File

@@ -2,11 +2,10 @@ 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 request from 'supertest';
import { AppModule } from '../app';
import { AppModule } from '../src/app';
import {
acceptInvite,
createWorkspace,
@@ -133,7 +132,7 @@ test('should share a page', async t => {
t.is(pages.length, 1, 'failed to get shared pages');
t.is(pages[0], 'page1', 'failed to get shared page: page1');
const msg1 = await sharePage(app, u2.token.token, workspace.id, 'page2');
const msg1 = await sharePage(app, u2.token.token, 'not_exists_ws', 'page2');
t.is(msg1, 'Permission denied', 'unauthorized user can share page');
const msg2 = await revokePage(app, u2.token.token, 'not_exists_ws', 'page2');
t.is(msg2, 'Permission denied', 'unauthorized user can share page');

View File

@@ -16,8 +16,8 @@
"verbatimModuleSyntax": false,
"rootDir": "./src"
},
"include": ["./src", "package.json"],
"exclude": ["dist", "node_modules", "./src/tests"],
"include": ["src"],
"exclude": ["dist", "lib", "tests"],
"references": [
{
"path": "./tsconfig.node.json"

View File

@@ -18,5 +18,6 @@
"path": "../../tests/kit"
}
],
"include": ["scripts", "package.json"]
"include": ["scripts", "package.json"],
"exclude": ["tests"]
}