Skip to content

Commit

Permalink
feat: init cron job for copilot test
Browse files Browse the repository at this point in the history
  • Loading branch information
darkskygit committed Nov 14, 2024
1 parent a08d728 commit 31ce694
Show file tree
Hide file tree
Showing 3 changed files with 131 additions and 16 deletions.
35 changes: 35 additions & 0 deletions .github/helm/affine/charts/graphql/templates/copilot-test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
apiVersion: batch/v1
kind: CronJob
metadata:
name: {{ include "graphql.fullname" . }}-copilot-test
labels:
{{- include "graphql.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": post-install,post-upgrade
"helm.sh/hook-weight": "1"
"helm.sh/hook-delete-policy": before-hook-creation
spec:
schedule: "0 8 * * *"
jobTemplate:
spec:
template:
spec:
serviceAccountName: {{ include "graphql.serviceAccountName" . }}
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
command: ["yarn", "test:copilot:e2e"]
env:
- name: COPILOT_E2E_ENDPOINT
value: "{{ include "graphql.fullname" . }}.{{ .Release.Namespace }}.svc.cluster.local"
- name: DATABASE_PASSWORD
valueFrom:
secretKeyRef:
name: pg-postgresql
key: postgres-password
resources:
requests:
cpu: '100m'
memory: '200Mi'
restartPolicy: Never
backoffLimit: 1
2 changes: 1 addition & 1 deletion packages/backend/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"@prisma/client": "^5.15.0",
"@prisma/instrumentation": "^5.15.0",
"@socket.io/redis-adapter": "^8.3.0",
"ava": "^6.1.2",
"cookie-parser": "^1.4.6",
"dotenv": "^16.4.5",
"express": "^4.19.2",
Expand Down Expand Up @@ -109,7 +110,6 @@
"@types/on-headers": "^1.0.3",
"@types/sinon": "^17.0.3",
"@types/supertest": "^6.0.2",
"ava": "^6.1.2",
"c8": "^10.0.0",
"nodemon": "^3.1.0",
"sinon": "^19.0.0",
Expand Down
110 changes: 95 additions & 15 deletions packages/backend/server/tests/copilot-provider.e2e.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { randomUUID } from 'node:crypto';
import { randomInt, randomUUID } from 'node:crypto';

import { createRandomAIUser } from '@affine-test/kit/utils/cloud';
import { hash } from '@node-rs/argon2';
import type { ExecutionContext, TestFn } from 'ava';
import ava from 'ava';
import { z } from 'zod';

import { createWorkspace } from './utils';
import {
Expand Down Expand Up @@ -47,20 +48,14 @@ const runIfCopilotConfigured = test.macro(
}
);

export const runPrisma = async <T>(
const runPrisma = async <T>(
cb: (
prisma: InstanceType<
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
typeof import('../../../../packages/backend/server/node_modules/@prisma/client').PrismaClient
typeof import('../node_modules/@prisma/client').PrismaClient
>
) => Promise<T>
): Promise<T> => {
const {
PrismaClient,
// eslint-disable-next-line @typescript-eslint/no-var-requires
} = await import(
'../../../../packages/backend/server/node_modules/@prisma/client'
);
const { PrismaClient } = await import('../node_modules/@prisma/client');
const client = new PrismaClient();
await client.$connect();
try {
Expand All @@ -70,14 +65,99 @@ export const runPrisma = async <T>(
}
};

const cloudUserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
password: z.string(),
});

function randomName() {
return Array.from({ length: 10 }, () =>
String.fromCharCode(randomInt(65, 90))
)
.join('')
.toLowerCase();
}

async function createRandomAIUser(): Promise<{
name: string;
email: string;
password: string;
id: string;
sessionId: string;
}> {
const name = randomName();
const email = `${name}@affine.fail`;
const user = { name, email, password: '123456' };
const result = await runPrisma(async client => {
const freeFeatureId = await client.feature
.findFirst({
where: { feature: 'free_plan_v1' },
select: { id: true },
orderBy: { version: 'desc' },
})
.then(f => f!.id);
const aiFeatureId = await client.feature
.findFirst({
where: { feature: 'unlimited_copilot' },
select: { id: true },
orderBy: { version: 'desc' },
})
.then(f => f!.id);

const { id: userId } = await client.user.create({
data: {
...user,
emailVerifiedAt: new Date(),
password: await hash(user.password),
features: {
create: [
{
reason: 'created by test case',
activated: true,
featureId: freeFeatureId,
},
{
reason: 'created by test case',
activated: true,
featureId: aiFeatureId,
},
],
},
},
});

const { id: sessionId } = await client.session.create({ data: {} });
await client.userSession.create({
data: {
sessionId,
userId,
// half an hour
expiresAt: new Date(Date.now() + 60 * 30 * 1000),
},
});

return await client.user
.findUnique({
where: {
email: user.email,
},
})
.then(r => ({ ...r, sessionId }));
});
cloudUserSchema.parse(result);
return {
...result,
password: user.password,
} as any;
}

test.before(async t => {
if (!isCopilotConfigured) return;
const { endpoint } = e2eConfig;

const { email, sessionId: token } = await createRandomAIUser(
'affine.fail',
runPrisma
);
const { email, sessionId: token } = await createRandomAIUser();
const app = { getHttpServer: () => endpoint } as any;
const { id } = await createWorkspace(app, token);

Expand Down

0 comments on commit 31ce694

Please sign in to comment.