forked from anc95/ChatGPT-CodeReview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-review.ts
More file actions
206 lines (183 loc) · 6.2 KB
/
test-review.ts
File metadata and controls
206 lines (183 loc) · 6.2 KB
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
206
import { Chat } from "./src/chat.js";
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
if (!OPENAI_API_KEY) {
console.error("OPENAI_API_KEY 환경변수를 설정해주세요.");
console.error("사용법: OPENAI_API_KEY=sk-... npx tsx test-review.ts");
process.exit(1);
}
const chat = new Chat(OPENAI_API_KEY);
const testInput = `## 리뷰 지침 (STRICT)
다음을 반드시 준수하세요 — 어기면 산출물은 실패로 간주됩니다.
- **스코프: 이 파일의 Diff만** 다룹니다. 다른 파일/일반론 언급 금지.
- **근거 필수:** 모든 지적은 Diff의 \`+\`(추가) 라인에 근거해, 해당 코드 스니펫을 인라인 코드로 포함하세요.
- **전역 컨텍스트는 참고용**입니다. 스코프를 벗어난 내용이 필요하면 그 항목은 **작성하지 마세요**.
- **우선순위:** 버그/보안/성능/테스트 중심. 사소한 스타일/개인 취향 금지.
- **스코프 위반 방지:** 다른 파일이나 일반 베스트 프랙티스만을 언급하려 할 경우, 해당 코멘트는 생략합니다.
# File: src/services/userService.ts
## Diff
\`\`\`diff
@@ -1,15 +1,89 @@
-import { db } from '../db';
+import { db } from '../db';
+import { Redis } from 'ioredis';
+import { hash, compare } from 'bcrypt';
+
+const redis = new Redis(process.env.REDIS_URL);
+const JWT_SECRET = "super-secret-key-12345";
+
+interface User {
+ id: string;
+ email: string;
+ password: string;
+ role: 'admin' | 'user';
+}
+
+export async function authenticateUser(email: string, password: string) {
+ const query = \`SELECT * FROM users WHERE email = '\${email}'\`;
+ const result = await db.query(query);
+
+ if (result.rows.length === 0) {
+ return null;
+ }
+
+ const user = result.rows[0];
+ const isValid = await compare(password, user.password);
+
+ if (isValid) {
+ const token = generateToken(user);
+ await redis.set(\`session:\${user.id}\`, token);
+ return { user, token };
+ }
+
+ return null;
+}
+
+export async function getUserById(id: string): Promise<User> {
+ const cached = await redis.get(\`user:\${id}\`);
+ if (cached) {
+ return JSON.parse(cached);
+ }
+
+ const result = await db.query('SELECT * FROM users WHERE id = $1', [id]);
+ const user = result.rows[0];
+
+ redis.set(\`user:\${id}\`, JSON.stringify(user), 'EX', 3600);
+ return user;
+}
+
+export async function updateUserRole(userId: string, newRole: string) {
+ const user = await getUserById(userId);
+
+ if (user.role == 'admin') {
+ throw new Error('Cannot modify admin users');
+ }
+
+ await db.query(
+ \`UPDATE users SET role = '\${newRole}' WHERE id = '\${userId}'\`
+ );
+
+ redis.del(\`user:\${userId}\`);
+}
+
+export async function deleteUser(userId: string) {
+ try {
+ await db.query('DELETE FROM users WHERE id = $1', [userId]);
+ await redis.del(\`user:\${userId}\`);
+ await redis.del(\`session:\${userId}\`);
+ } catch (e) {
+ }
+}
+
+export function processUsers(users: User[]) {
+ const results = [];
+ for (let i = 0; i <= users.length; i++) {
+ const user = users[i];
+ if (user.role = 'admin') {
+ results.push(user.email.toUpperCase());
+ }
+ }
+ return results;
+}
+
+function generateToken(user: User): string {
+ return Buffer.from(JSON.stringify({
+ id: user.id,
+ email: user.email,
+ exp: Date.now() + 86400000
+ })).toString('base64');
+}
\`\`\`
---
# PR 메타 정보 (참고용)
## PR 제목
사용자 인증 및 캐싱 기능 추가
## 커밋 메시지
feat: add user authentication with Redis caching
`;
const summaryInput = `커밋 메시지:
feat: add user authentication with Redis caching
변경된 파일:
- src/services/userService.ts (added)
- src/db/index.ts (modified)
전체 diff:
@@ -1,15 +1,89 @@
-import { db } from '../db';
+import { db } from '../db';
+import { Redis } from 'ioredis';
+import { hash, compare } from 'bcrypt';
+
+const redis = new Redis(process.env.REDIS_URL);
+const JWT_SECRET = "super-secret-key-12345";
... (이하 동일)
`;
console.log("=".repeat(60));
console.log("🔍 코드 리뷰 테스트");
console.log("=".repeat(60));
console.log("\n📝 테스트할 코드에 의도적으로 포함된 문제들:");
console.log(" 1. SQL 인젝션 (line 17, 56-57)");
console.log(" 2. 하드코딩된 JWT 시크릿 (line 6)");
console.log(" 3. 빈 catch 블록 (line 69)");
console.log(" 4. off-by-one 에러 (line 73: i <= users.length)");
console.log(" 5. 할당 vs 비교 오류 (line 75: user.role = 'admin')");
console.log(" 6. null 체크 없이 접근 (line 43: user가 undefined일 수 있음)");
console.log(" 7. == 대신 === 사용해야 함 (line 51)");
console.log("\n");
async function runTests() {
console.log("⏳ 코드 리뷰 요청 중...\n");
try {
const reviewResult = await chat.codeReview(testInput);
console.log("📋 리뷰 결과:");
console.log("-".repeat(40));
console.log(`LGTM: ${reviewResult.lgtm}`);
console.log(`발견된 이슈: ${reviewResult.comments.length}개\n`);
for (const comment of reviewResult.comments) {
const emoji = comment.severity === "critical" ? "🔴" : "🟠";
console.log(`${emoji} [${comment.severity.toUpperCase()}] Line ${comment.line}`);
console.log(` 카테고리: ${comment.category}`);
console.log(` 내용: ${comment.body}`);
console.log();
}
console.log("\n" + "=".repeat(60));
console.log("📊 PR 요약 테스트");
console.log("=".repeat(60));
console.log("\n⏳ PR 요약 생성 중...\n");
const summaryResult = await chat.summarizeChanges(summaryInput);
console.log("📋 요약 결과:");
console.log("-".repeat(40));
console.log(`변경 유형: ${summaryResult.changeType}`);
console.log(`제목: ${summaryResult.title}`);
console.log(`\n요약:\n${summaryResult.summary}`);
if (summaryResult.walkthrough.length > 0) {
console.log("\n📂 워크스루:");
for (const w of summaryResult.walkthrough) {
console.log(` - ${w.file}: ${w.changes} (${w.intent})`);
}
}
if (summaryResult.affectedAreas.length > 0) {
console.log(`\n🎯 영향 범위: ${summaryResult.affectedAreas.join(", ")}`);
}
} catch (e) {
console.error("❌ 오류 발생:", e);
}
}
runTests();