-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathtypeorm.test.ts
205 lines (175 loc) · 6 KB
/
typeorm.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import request from 'supertest';
import { Entity, Column, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
import { EntityManager, Unique } from 'typeorm';
import { generateDBOSTestConfig, setUpDBOSTestDb } from './helpers';
import {
TestingRuntime,
Transaction,
OrmEntities,
TransactionContext,
Authentication,
MiddlewareContext,
GetApi,
HandlerContext,
RequiredRole,
PostApi,
} from '../src';
import { DBOSConfig } from '../src/dbos-executor';
import { v1 as uuidv1 } from 'uuid';
import { UserDatabaseName } from '../src/user_database';
import { createInternalTestRuntime } from '../src/testing/testing_runtime';
import { DBOSNotAuthorizedError } from '../src/error';
/**
* Funtions used in tests.
*/
@Entity()
export class KV {
@PrimaryColumn()
id: string = 't';
@Column()
value: string = 'v';
}
let globalCnt = 0;
type TestTransactionContext = TransactionContext<EntityManager>;
@OrmEntities()
export class NoEntities {}
@OrmEntities([KV])
class KVController {
@Transaction()
static async testTxn(txnCtxt: TestTransactionContext, id: string, value: string) {
const kv: KV = new KV();
kv.id = id;
kv.value = value;
const res = await txnCtxt.client.save(kv);
globalCnt += 1;
return res.id;
}
@Transaction({ readOnly: true })
static async readTxn(txnCtxt: TestTransactionContext, id: string) {
globalCnt += 1;
const kvp = await txnCtxt.client.findOneBy(KV, { id: id });
return Promise.resolve(kvp?.value || '<Not Found>');
}
}
describe('typeorm-tests', () => {
let config: DBOSConfig;
let testRuntime: TestingRuntime;
beforeAll(async () => {
config = generateDBOSTestConfig(UserDatabaseName.TYPEORM);
await setUpDBOSTestDb(config);
});
beforeEach(async () => {
globalCnt = 0;
testRuntime = await createInternalTestRuntime(undefined, config);
await testRuntime.dropUserSchema();
await testRuntime.createUserSchema();
});
afterEach(async () => {
await testRuntime.destroy();
});
test('simple-typeorm', async () => {
const workUUID = uuidv1();
await expect(testRuntime.invoke(KVController, workUUID).testTxn('test', 'value')).resolves.toBe('test');
await expect(testRuntime.invoke(KVController, workUUID).testTxn('test', 'value')).resolves.toBe('test');
});
test('typeorm-duplicate-transaction', async () => {
// Run two transactions concurrently with the same UUID.
// Both should return the correct result but only one should execute.
const workUUID = uuidv1();
let results = await Promise.allSettled([
testRuntime.invoke(KVController, workUUID).testTxn('oaootest', 'oaoovalue'),
testRuntime.invoke(KVController, workUUID).testTxn('oaootest', 'oaoovalue'),
]);
expect((results[0] as PromiseFulfilledResult<string>).value).toBe('oaootest');
expect((results[1] as PromiseFulfilledResult<string>).value).toBe('oaootest');
expect(globalCnt).toBe(1);
// Read-only transactions would execute twice.
globalCnt = 0;
const readUUID = uuidv1();
results = await Promise.allSettled([
testRuntime.invoke(KVController, readUUID).readTxn('oaootest'),
testRuntime.invoke(KVController, readUUID).readTxn('oaootest'),
]);
expect((results[0] as PromiseFulfilledResult<string>).value).toBe('oaoovalue');
expect((results[1] as PromiseFulfilledResult<string>).value).toBe('oaoovalue');
expect(globalCnt).toBeGreaterThanOrEqual(1);
});
});
@Entity()
@Unique('onlyone', ['username'])
export class User {
@PrimaryGeneratedColumn('uuid')
id: string | undefined = undefined;
@Column()
username: string = 'user';
}
@OrmEntities([User])
@Authentication(UserManager.authMiddlware)
class UserManager {
@Transaction()
@PostApi('/register')
static async createUser(txnCtxt: TestTransactionContext, uname: string) {
const u: User = new User();
u.username = uname;
const res = await txnCtxt.client.save(u);
return res;
}
@GetApi('/hello')
@RequiredRole(['user'])
static async hello(hCtxt: HandlerContext) {
return Promise.resolve({ messge: 'hello ' + hCtxt.authenticatedUser });
}
static async authMiddlware(ctx: MiddlewareContext) {
const cfg = ctx.getConfig<string>('shouldExist', 'does not exist');
if (cfg !== 'exists') {
throw Error('Auth is misconfigured.');
}
if (!ctx.requiredRole || !ctx.requiredRole.length) {
return;
}
const { user } = ctx.koaContext.query;
if (!user) {
throw new DBOSNotAuthorizedError('User not provided', 401);
}
const u = await ctx.query((dbClient: EntityManager, uname: string) => {
return dbClient.findOneBy(User, { username: uname });
}, user as string);
if (!u) {
throw new DBOSNotAuthorizedError('User does not exist', 403);
}
ctx.logger.info(`Allowed in user: ${u.username}`);
return {
authenticatedUser: u.username,
authenticatedRoles: ['user'],
};
}
}
describe('typeorm-auth-tests', () => {
let config: DBOSConfig;
let testRuntime: TestingRuntime;
beforeAll(async () => {
config = generateDBOSTestConfig(UserDatabaseName.TYPEORM);
await setUpDBOSTestDb(config);
});
beforeEach(async () => {
globalCnt = 0;
testRuntime = await createInternalTestRuntime(undefined, config);
await testRuntime.dropUserSchema();
await testRuntime.createUserSchema();
});
afterEach(async () => {
await testRuntime.destroy();
});
test('auth-typeorm', async () => {
// No user name
const response1 = await request(testRuntime.getHandlersCallback()).get('/hello');
expect(response1.statusCode).toBe(401);
// User name doesn't exist
const response2 = await request(testRuntime.getHandlersCallback()).get('/hello?user=paul');
expect(response2.statusCode).toBe(403);
const response3 = await request(testRuntime.getHandlersCallback()).post('/register').send({ uname: 'paul' });
expect(response3.statusCode).toBe(200);
const response4 = await request(testRuntime.getHandlersCallback()).get('/hello?user=paul');
expect(response4.statusCode).toBe(200);
});
});