[이제와서 시작하는 Python 마스터하기 #14] 테스트와 디버깅 전략
🏢 실전 한국 비즈니스 예제: 네이버쇼핑 상품 검증 시스템
네이버쇼핑에서 판매자가 등록하는 상품 정보의 정확성을 검증하는 시스템을 개발한다고 가정해봅시다. 이 시스템은 다음과 같은 기능이 필요합니다:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class ProductValidator:
"""상품 정보 검증기"""
def validate_business_number(self, business_number: str) -> bool:
"""사업자 번호 검증 (10자리 숫자)"""
if len(business_number) != 10 or not business_number.isdigit():
return False
# 사업자번호 체크썸 알고리즘 적용
return self._validate_checksum(business_number)
def validate_product_name(self, name: str) -> bool:
"""상품명 검증 (금지어 체크)"""
forbidden_words = ['짝퉁', '가짜', '복제품']
return not any(word in name for word in forbidden_words)
def validate_price(self, price: int, category: str) -> bool:
"""가격 검증 (카테고리별 최소가격)"""
min_prices = {'의류': 1000, '전자제품': 10000, '식품': 500}
return price >= min_prices.get(category, 1000)
def validate_stock(self, stock: int) -> bool:
"""재고 검증"""
return 0 <= stock <= 10000
이런 시스템에서는 각 검증 로직이 정확히 작동하는지 테스트하고, 오류 발생 시 빠르게 디버깅할 수 있어야 합니다. 잘못된 상품이 등록되면 고객 신뢰도 하락과 직결되기 때문입니다.
🧪 테스트와 디버깅의 중요성
테스트와 디버깅은 고품질 소프트웨어 개발의 핵심입니다. 버그를 조기에 발견하고 코드의 신뢰성을 보장합니다.
graph TB
subgraph "테스트 유형"
A[단위 테스트<br/>Unit Test] --> B[개별 함수/메서드]
C[통합 테스트<br/>Integration Test] --> D[모듈 간 상호작용]
E[시스템 테스트<br/>System Test] --> F[전체 시스템]
G[인수 테스트<br/>Acceptance Test] --> H[사용자 요구사항]
end
subgraph "디버깅 도구"
I[pdb] --> J[대화형 디버거]
K[logging] --> L[로그 기반 디버깅]
M[IDE 디버거] --> N[시각적 디버깅]
O[프로파일러] --> P[성능 분석]
end
🔬 unittest 프레임워크
unittest는 Python 표준 라이브러리에 포함된 테스트 프레임워크입니다.
[!TIP] unittest vs pytest
Python에는
unittest라는 기본 도구가 있지만, 요즘은pytest를 훨씬 더 많이 씁니다.unittest는 클래스를 만들어야 하고 코드가 길어지는 반면,pytest는 그냥 함수로 테스트를 짤 수 있어서 훨씬 간편하거든요! 이 글에서도 뒤쪽에서pytest를 다룹니다. 실무에서는pytest를 강력 추천합니다!
unittest 기본 사용법
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
import unittest
from typing import List, Dict, Any
# 테스트할 코드
class Calculator:
"""계산기 클래스"""
def add(self, a: float, b: float) -> float:
"""덧셈"""
return a + b
def subtract(self, a: float, b: float) -> float:
"""뺄셈"""
return a - b
def multiply(self, a: float, b: float) -> float:
"""곱셈"""
return a * b
def divide(self, a: float, b: float) -> float:
"""나눗셈"""
if b == 0:
raise ValueError("0으로 나눌 수 없습니다")
return a / b
def power(self, base: float, exponent: int) -> float:
"""거듭제곱"""
return base ** exponent
# 테스트 클래스
class TestCalculator(unittest.TestCase):
"""Calculator 테스트"""
def setUp(self):
"""각 테스트 전에 실행"""
self.calc = Calculator()
def tearDown(self):
"""각 테스트 후에 실행"""
# 정리 작업이 필요한 경우
pass
def test_add(self):
"""덧셈 테스트"""
self.assertEqual(self.calc.add(2, 3), 5)
self.assertEqual(self.calc.add(-1, 1), 0)
self.assertEqual(self.calc.add(0, 0), 0)
# 부동소수점 비교
self.assertAlmostEqual(self.calc.add(0.1, 0.2), 0.3, places=7)
def test_subtract(self):
"""뺄셈 테스트"""
self.assertEqual(self.calc.subtract(5, 3), 2)
self.assertEqual(self.calc.subtract(-1, -1), 0)
self.assertLess(self.calc.subtract(3, 5), 0)
def test_multiply(self):
"""곱셈 테스트"""
self.assertEqual(self.calc.multiply(3, 4), 12)
self.assertEqual(self.calc.multiply(-2, 3), -6)
self.assertEqual(self.calc.multiply(0, 100), 0)
def test_divide(self):
"""나눗셈 테스트"""
self.assertEqual(self.calc.divide(10, 2), 5)
self.assertAlmostEqual(self.calc.divide(1, 3), 0.333333, places=5)
# 예외 테스트
with self.assertRaises(ValueError) as context:
self.calc.divide(10, 0)
self.assertIn("0으로 나눌 수 없습니다", str(context.exception))
def test_power(self):
"""거듭제곱 테스트"""
self.assertEqual(self.calc.power(2, 3), 8)
self.assertEqual(self.calc.power(5, 0), 1)
self.assertEqual(self.calc.power(10, -1), 0.1)
# 테스트 실행
if __name__ == '__main__':
unittest.main()
고급 테스트 기법
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
207
208
209
import unittest
from unittest.mock import Mock, patch, MagicMock
import tempfile
import os
from datetime import datetime
# 테스트할 코드
class UserService:
"""사용자 서비스"""
def __init__(self, db_connection):
self.db = db_connection
def get_user(self, user_id: int) -> Dict:
"""사용자 조회"""
user = self.db.find_user(user_id)
if not user:
raise ValueError(f"사용자 {user_id}를 찾을 수 없습니다")
return user
def create_user(self, name: str, email: str) -> int:
"""사용자 생성"""
if not self.validate_email(email):
raise ValueError("잘못된 이메일 형식")
user_id = self.db.insert_user(name, email)
self.send_welcome_email(email)
return user_id
def validate_email(self, email: str) -> bool:
"""이메일 검증"""
import re
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(pattern, email) is not None
def send_welcome_email(self, email: str):
"""환영 이메일 발송"""
# 실제 이메일 발송 로직
pass
> [!TIP]
> **Mock(가짜)은 왜 쓰나요?**
>
> 테스트할 때 **실제 이메일을 보내거나, 실제 결제를 해버리면 안 되잖아요?**
> 그래서 "이메일을 보냈다고 치자", "결제가 성공했다고 치자"라고 **가짜 객체(Mock)**를 만들어서 테스트하는 겁니다.
> 외부 시스템(DB, API, 파일시스템 등)에 의존하지 않고 내 로직만 테스트하기 위해 필수적입니다!
# Mock을 사용한 테스트
class TestUserService(unittest.TestCase):
"""UserService 테스트"""
def setUp(self):
"""테스트 설정"""
self.mock_db = Mock()
self.service = UserService(self.mock_db)
def test_get_user_success(self):
"""사용자 조회 성공 테스트"""
# Mock 설정
expected_user = {'id': 1, 'name': 'John', 'email': 'john@example.com'}
self.mock_db.find_user.return_value = expected_user
# 테스트 실행
user = self.service.get_user(1)
# 검증
self.assertEqual(user, expected_user)
self.mock_db.find_user.assert_called_once_with(1)
def test_get_user_not_found(self):
"""사용자 조회 실패 테스트"""
self.mock_db.find_user.return_value = None
with self.assertRaises(ValueError) as context:
self.service.get_user(999)
self.assertIn("999를 찾을 수 없습니다", str(context.exception))
@patch('__main__.UserService.send_welcome_email')
def test_create_user(self, mock_send_email):
"""사용자 생성 테스트"""
# Mock 설정
self.mock_db.insert_user.return_value = 123
# 테스트 실행
user_id = self.service.create_user('Jane', 'jane@example.com')
# 검증
self.assertEqual(user_id, 123)
self.mock_db.insert_user.assert_called_once_with('Jane', 'jane@example.com')
mock_send_email.assert_called_once_with('jane@example.com')
def test_create_user_invalid_email(self):
"""잘못된 이메일로 사용자 생성 테스트"""
with self.assertRaises(ValueError) as context:
self.service.create_user('Bob', 'invalid-email')
self.assertIn("잘못된 이메일 형식", str(context.exception))
self.mock_db.insert_user.assert_not_called()
# 파일 시스템 테스트
class FileProcessor:
"""파일 처리기"""
def process_file(self, filepath: str) -> Dict[str, Any]:
"""파일 처리"""
if not os.path.exists(filepath):
raise FileNotFoundError(f"파일을 찾을 수 없습니다: {filepath}")
with open(filepath, 'r') as f:
content = f.read()
return {
'lines': len(content.splitlines()),
'words': len(content.split()),
'chars': len(content),
'processed_at': datetime.now().isoformat()
}
def save_result(self, result: Dict, output_path: str):
"""결과 저장"""
import json
with open(output_path, 'w') as f:
json.dump(result, f, indent=2)
class TestFileProcessor(unittest.TestCase):
"""FileProcessor 테스트"""
def setUp(self):
"""테스트 설정"""
self.processor = FileProcessor()
self.temp_dir = tempfile.mkdtemp()
def tearDown(self):
"""테스트 정리"""
import shutil
shutil.rmtree(self.temp_dir)
def test_process_file(self):
"""파일 처리 테스트"""
# 테스트 파일 생성
test_content = "Hello World\nPython Testing\nLine 3"
test_file = os.path.join(self.temp_dir, 'test.txt')
with open(test_file, 'w') as f:
f.write(test_content)
# 테스트 실행
result = self.processor.process_file(test_file)
# 검증
self.assertEqual(result['lines'], 3)
self.assertEqual(result['words'], 6)
self.assertEqual(result['chars'], len(test_content))
self.assertIn('processed_at', result)
def test_process_nonexistent_file(self):
"""존재하지 않는 파일 처리 테스트"""
with self.assertRaises(FileNotFoundError):
self.processor.process_file('/nonexistent/file.txt')
def test_save_result(self):
"""결과 저장 테스트"""
result = {'test': 'data', 'number': 42}
output_file = os.path.join(self.temp_dir, 'output.json')
self.processor.save_result(result, output_file)
# 저장된 파일 확인
self.assertTrue(os.path.exists(output_file))
import json
with open(output_file, 'r') as f:
saved_data = json.load(f)
self.assertEqual(saved_data, result)
# 테스트 스위트와 테스트 러너
def create_test_suite():
"""테스트 스위트 생성"""
suite = unittest.TestSuite()
# 개별 테스트 추가
suite.addTest(TestCalculator('test_add'))
suite.addTest(TestCalculator('test_divide'))
# 전체 테스트 클래스 추가
suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestUserService))
return suite
# 커스텀 테스트 러너
class CustomTestRunner(unittest.TextTestRunner):
"""커스텀 테스트 러너"""
def run(self, test):
"""테스트 실행"""
print("=" * 70)
print("테스트 시작")
print("=" * 70)
result = super().run(test)
print("=" * 70)
print(f"실행: {result.testsRun}, 성공: {result.testsRun - len(result.failures) - len(result.errors)}")
print(f"실패: {len(result.failures)}, 오류: {len(result.errors)}")
print("=" * 70)
return result
🚀 pytest 프레임워크
pytest는 더 간단하고 강력한 테스트 프레임워크입니다.
[!NOTE] pytest 설치하기
pytest는 표준 라이브러리가 아니라서 설치가 필요합니다.
1pip install pytest실행할 때는 터미널에서 그냥
pytest라고만 치면, 현재 폴더의test_*.py파일들을 알아서 찾아서 실행해줍니다!
pytest 기본 사용법
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
import pytest
from typing import List, Optional
import requests
# 테스트할 코드
class TodoService:
"""할일 서비스"""
def __init__(self, api_url: str):
self.api_url = api_url
self.todos: List[Dict] = []
def add_todo(self, title: str, completed: bool = False) -> Dict:
"""할일 추가"""
if not title:
raise ValueError("제목은 필수입니다")
todo = {
'id': len(self.todos) + 1,
'title': title,
'completed': completed
}
self.todos.append(todo)
return todo
def get_todo(self, todo_id: int) -> Optional[Dict]:
"""할일 조회"""
for todo in self.todos:
if todo['id'] == todo_id:
return todo
return None
def update_todo(self, todo_id: int, **kwargs) -> Optional[Dict]:
"""할일 수정"""
todo = self.get_todo(todo_id)
if todo:
todo.update(kwargs)
return todo
return None
def delete_todo(self, todo_id: int) -> bool:
"""할일 삭제"""
for i, todo in enumerate(self.todos):
if todo['id'] == todo_id:
del self.todos[i]
return True
return False
def fetch_remote_todos(self) -> List[Dict]:
"""원격 API에서 할일 가져오기"""
response = requests.get(f"{self.api_url}/todos")
response.raise_for_status()
return response.json()
# pytest 테스트
class TestTodoService:
"""TodoService 테스트"""
@pytest.fixture
def service(self):
"""테스트용 서비스 인스턴스"""
return TodoService("https://api.example.com")
@pytest.fixture
def sample_todos(self):
"""샘플 할일 목록"""
return [
{'title': 'Buy milk', 'completed': False},
{'title': 'Write tests', 'completed': True},
{'title': 'Deploy app', 'completed': False}
]
def test_add_todo(self, service):
"""할일 추가 테스트"""
todo = service.add_todo("Test todo")
assert todo['id'] == 1
assert todo['title'] == "Test todo"
assert todo['completed'] is False
assert len(service.todos) == 1
def test_add_todo_empty_title(self, service):
"""빈 제목으로 할일 추가 테스트"""
with pytest.raises(ValueError, match="제목은 필수입니다"):
service.add_todo("")
@pytest.mark.parametrize("title,completed,expected_id", [
("First", False, 1),
("Second", True, 2),
("Third", False, 3),
])
def test_add_multiple_todos(self, service, title, completed, expected_id):
"""여러 할일 추가 테스트 (파라미터화)"""
todo = service.add_todo(title, completed)
assert todo['id'] == expected_id
assert todo['title'] == title
assert todo['completed'] == completed
def test_get_todo(self, service, sample_todos):
"""할일 조회 테스트"""
# 샘플 데이터 추가
for todo_data in sample_todos:
service.add_todo(**todo_data)
# 조회 테스트
todo = service.get_todo(2)
assert todo is not None
assert todo['title'] == 'Write tests'
assert todo['completed'] is True
# 존재하지 않는 할일
assert service.get_todo(999) is None
def test_update_todo(self, service):
"""할일 수정 테스트"""
# 할일 추가
todo = service.add_todo("Original title")
todo_id = todo['id']
# 수정
updated = service.update_todo(todo_id, title="Updated title", completed=True)
assert updated is not None
assert updated['title'] == "Updated title"
assert updated['completed'] is True
# 존재하지 않는 할일 수정
assert service.update_todo(999, title="Test") is None
def test_delete_todo(self, service):
"""할일 삭제 테스트"""
# 할일 추가
todo1 = service.add_todo("Todo 1")
todo2 = service.add_todo("Todo 2")
# 삭제
assert service.delete_todo(todo1['id']) is True
assert len(service.todos) == 1
assert service.get_todo(todo1['id']) is None
# 이미 삭제된 할일
assert service.delete_todo(todo1['id']) is False
@pytest.mark.integration
def test_fetch_remote_todos(self, service, requests_mock):
"""원격 API 통합 테스트"""
# Mock 응답 설정
mock_data = [
{'id': 1, 'title': 'Remote todo 1', 'completed': False},
{'id': 2, 'title': 'Remote todo 2', 'completed': True}
]
requests_mock.get(f"{service.api_url}/todos", json=mock_data)
# 테스트 실행
todos = service.fetch_remote_todos()
assert len(todos) == 2
assert todos[0]['title'] == 'Remote todo 1'
### 🔧 pytest Fixtures 고급 활용
```python
# Fixture 고급 사용법과 Best Practices
import pytest
from typing import Generator, Any
import tempfile
import shutil
from pathlib import Path
from datetime import datetime
# 1. Fixture Scope 관리
@pytest.fixture(scope="session")
def app_config():
"""세션 레벨 설정 - 전체 테스트 세션동안 한 번만 생성"""
return {
'debug': True,
'testing': True,
'database_url': 'sqlite:///:memory:',
'api_key': 'test-key-12345'
}
@pytest.fixture(scope="module")
def database(app_config):
"""모듈 레벨 데이터베이스 - 모듈당 한 번 생성"""
import sqlite3
# Setup
conn = sqlite3.connect(':memory:')
conn.execute("""
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute("""
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
user_id INTEGER,
title TEXT NOT NULL,
content TEXT,
published BOOLEAN DEFAULT 0,
FOREIGN KEY(user_id) REFERENCES users(id)
)
""")
yield conn
# Teardown
conn.close()
@pytest.fixture(scope="class")
def api_client(app_config):
"""클래스 레벨 API 클라이언트"""
from unittest.mock import Mock
client = Mock()
client.base_url = "https://test-api.example.com"
client.headers = {'Authorization': f"Bearer {app_config['api_key']}"}
return client
@pytest.fixture(scope="function") # 기본값
def temp_workspace() -> Generator[Path, None, None]:
"""함수 레벨 임시 작업 공간"""
# Setup
workspace = Path(tempfile.mkdtemp())
# 기본 디렉토리 구조 생성
(workspace / "src").mkdir()
(workspace / "tests").mkdir()
(workspace / "data").mkdir()
yield workspace
# Teardown
shutil.rmtree(workspace)
# 2. Fixture 의존성 관리
@pytest.fixture
def user_repository(database):
"""사용자 저장소 fixture"""
class UserRepository:
def __init__(self, conn):
self.conn = conn
def create_user(self, name: str, email: str) -> int:
cursor = self.conn.execute(
"INSERT INTO users (name, email) VALUES (?, ?)",
(name, email)
)
self.conn.commit()
return cursor.lastrowid
def get_user(self, user_id: int):
cursor = self.conn.execute(
"SELECT * FROM users WHERE id = ?",
(user_id,)
)
row = cursor.fetchone()
if row:
return {'id': row[0], 'name': row[1], 'email': row[2]}
return None
def update_user(self, user_id: int, **kwargs):
fields = ', '.join(f"{k} = ?" for k in kwargs.keys())
values = list(kwargs.values()) + [user_id]
self.conn.execute(
f"UPDATE users SET {fields} WHERE id = ?",
values
)
self.conn.commit()
return UserRepository(database)
@pytest.fixture
def post_repository(database):
"""포스트 저장소 fixture"""
class PostRepository:
def __init__(self, conn):
self.conn = conn
def create_post(self, user_id: int, title: str, content: str = "") -> int:
cursor = self.conn.execute(
"INSERT INTO posts (user_id, title, content) VALUES (?, ?, ?)",
(user_id, title, content)
)
self.conn.commit()
return cursor.lastrowid
def get_user_posts(self, user_id: int):
cursor = self.conn.execute(
"SELECT * FROM posts WHERE user_id = ?",
(user_id,)
)
return [
{'id': row[0], 'user_id': row[1], 'title': row[2],
'content': row[3], 'published': bool(row[4])}
for row in cursor.fetchall()
]
return PostRepository(database)
@pytest.fixture
def sample_user(user_repository):
"""샘플 사용자 생성"""
user_id = user_repository.create_user("Test User", "test@example.com")
return {'id': user_id, 'name': "Test User", 'email': "test@example.com"}
@pytest.fixture
def sample_posts(post_repository, sample_user):
"""샘플 포스트 생성"""
posts = []
for i in range(3):
post_id = post_repository.create_post(
sample_user['id'],
f"Post {i+1}",
f"Content for post {i+1}"
)
posts.append({
'id': post_id,
'user_id': sample_user['id'],
'title': f"Post {i+1}",
'content': f"Content for post {i+1}"
})
return posts
# 3. Parametrized Fixtures
@pytest.fixture(params=['sqlite', 'postgresql', 'mysql'])
def db_engine(request):
"""다양한 데이터베이스 엔진 테스트"""
engine_type = request.param
if engine_type == 'sqlite':
import sqlite3
conn = sqlite3.connect(':memory:')
elif engine_type == 'postgresql':
# PostgreSQL 연결 모의
from unittest.mock import Mock
conn = Mock()
conn.engine_type = 'postgresql'
else: # mysql
from unittest.mock import Mock
conn = Mock()
conn.engine_type = 'mysql'
yield conn
if hasattr(conn, 'close'):
conn.close()
@pytest.fixture(params=[
{'format': 'json', 'ext': '.json'},
{'format': 'csv', 'ext': '.csv'},
{'format': 'xml', 'ext': '.xml'}
], ids=['json', 'csv', 'xml'])
def export_format(request):
"""다양한 내보내기 형식"""
return request.param
# 4. Factory Fixtures
@pytest.fixture
def user_factory(user_repository):
"""사용자 생성 팩토리"""
created_users = []
def _create_user(name: str = None, email: str = None, **kwargs):
if name is None:
name = f"User_{datetime.now().timestamp()}"
if email is None:
email = f"{name.lower()}@example.com"
user_id = user_repository.create_user(name, email)
user = {'id': user_id, 'name': name, 'email': email, **kwargs}
created_users.append(user)
return user
yield _create_user
# Cleanup - 생성된 모든 사용자 정리
# for user in created_users:
# user_repository.delete_user(user['id'])
@pytest.fixture
def post_factory(post_repository):
"""포스트 생성 팩토리"""
def _create_post(user_id: int, title: str = None, **kwargs):
if title is None:
title = f"Post at {datetime.now()}"
post_id = post_repository.create_post(user_id, title, **kwargs)
return {
'id': post_id,
'user_id': user_id,
'title': title,
**kwargs
}
return _create_post
# 5. Fixture 활용 테스트
class TestUserSystem:
"""사용자 시스템 통합 테스트"""
def test_user_creation(self, user_factory):
"""사용자 생성 테스트"""
user1 = user_factory(name="Alice")
user2 = user_factory(name="Bob", email="bob@test.com")
assert user1['name'] == "Alice"
assert user1['email'] == "alice@example.com"
assert user2['email'] == "bob@test.com"
def test_user_with_posts(self, user_factory, post_factory, post_repository):
"""사용자와 포스트 관계 테스트"""
# 사용자 생성
user = user_factory(name="Author")
# 포스트 생성
post1 = post_factory(user['id'], title="First Post")
post2 = post_factory(user['id'], title="Second Post")
# 검증
user_posts = post_repository.get_user_posts(user['id'])
assert len(user_posts) == 2
assert user_posts[0]['title'] == "First Post"
@pytest.mark.parametrize("num_users,num_posts_each", [
(2, 3),
(3, 5),
(1, 10),
])
def test_multiple_users_and_posts(
self, user_factory, post_factory, database,
num_users, num_posts_each
):
"""여러 사용자와 포스트 생성 테스트"""
users = [user_factory(name=f"User{i}") for i in range(num_users)]
for user in users:
for j in range(num_posts_each):
post_factory(user['id'], title=f"Post {j+1} by {user['name']}")
# 전체 포스트 수 확인
cursor = database.execute("SELECT COUNT(*) FROM posts")
total_posts = cursor.fetchone()[0]
assert total_posts == num_users * num_posts_each
# 6. Autouse Fixtures
@pytest.fixture(autouse=True)
def reset_database_sequence(database):
"""각 테스트 전 시퀀스 리셋 (자동 실행)"""
database.execute("DELETE FROM sqlite_sequence")
database.commit()
yield
# 테스트 후 정리 작업
@pytest.fixture(autouse=True, scope="session")
def configure_test_environment():
"""테스트 환경 설정 (세션당 한 번)"""
import os
# 테스트 환경 변수 설정
original_env = os.environ.get('ENVIRONMENT')
os.environ['ENVIRONMENT'] = 'testing'
yield
# 원래 환경으로 복구
if original_env:
os.environ['ENVIRONMENT'] = original_env
else:
del os.environ['ENVIRONMENT']
# 7. Fixture Request 객체 활용
@pytest.fixture
def dynamic_fixture(request):
"""동적 fixture 설정"""
# 마커에서 파라미터 가져오기
marker = request.node.get_closest_marker("fixture_params")
if marker:
params = marker.kwargs
else:
params = {}
# 테스트 이름 활용
test_name = request.node.name
return {
'test_name': test_name,
'params': params,
'timestamp': datetime.now()
}
@pytest.mark.fixture_params(timeout=30, retries=3)
def test_with_dynamic_fixture(dynamic_fixture):
"""동적 fixture 활용 테스트"""
assert dynamic_fixture['params']['timeout'] == 30
assert dynamic_fixture['params']['retries'] == 3
# 8. Fixture 마크업과 메타데이터
@pytest.fixture
def monitored_operation(request):
"""모니터링된 작업 fixture"""
import time
start_time = time.time()
test_name = request.node.name
def _operation_info():
return {
'test': test_name,
'elapsed': time.time() - start_time,
'status': 'running'
}
yield _operation_info
# 테스트 완료 후 로깅
elapsed = time.time() - start_time
print(f"\n테스트 '{test_name}' 완료: {elapsed:.2f}초")
def test_user_repository(user_repository):
"""사용자 저장소 테스트"""
# 사용자 생성
user_id = user_repository.create_user("John Doe", "john@example.com")
assert user_id == 1
# 사용자 조회
user = user_repository.get_user(user_id)
assert user['name'] == "John Doe"
assert user['email'] == "john@example.com"
# 커스텀 마커
@pytest.mark.slow
@pytest.mark.requires_network
def test_slow_network_operation():
"""느린 네트워크 작업 테스트"""
import time
time.sleep(2)
# 실제 네트워크 작업
assert True
# pytest.ini 설정 예시
"""
[pytest]
markers =
slow: marks tests as slow (deselect with '-m "not slow"')
integration: marks tests as integration tests
requires_network: marks tests that require network access
testpaths = tests
python_files = test_*.py *_test.py
python_classes = Test*
python_functions = test_*
addopts =
--verbose
--strict-markers
--tb=short
--cov=myproject
--cov-report=html
"""
🐛 디버깅 기법
Python은 다양한 디버깅 도구와 기법을 제공합니다.
pdb 디버거
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
import pdb
from typing import List, Dict
def complex_calculation(data: List[int]) -> Dict[str, float]:
"""복잡한 계산 함수"""
result = {
'sum': 0,
'average': 0,
'max': float('-inf'),
'min': float('inf')
}
# 디버깅 포인트 설정
pdb.set_trace()
for i, value in enumerate(data):
result['sum'] += value
if value > result['max']:
result['max'] = value
if value < result['min']:
result['min'] = value
# 조건부 브레이크포인트
if value < 0:
import pdb; pdb.set_trace()
result['average'] = result['sum'] / len(data) if data else 0
return result
# pdb 명령어 예시
"""
pdb 명령어:
- l (list): 현재 코드 표시
- n (next): 다음 줄 실행
- s (step): 함수 내부로 들어가기
- c (continue): 계속 실행
- b (break): 브레이크포인트 설정
- p (print): 변수 값 출력
- pp (pretty print): 예쁘게 출력
- h (help): 도움말
- q (quit): 종료
"""
# 디버깅 데코레이터
def debug_on_error(func):
"""오류 발생 시 디버거 실행"""
import functools
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
import pdb
import sys
import traceback
traceback.print_exc()
print("\n디버거를 시작합니다...")
# 예외 정보 저장
exc_type, exc_value, exc_traceback = sys.exc_info()
# 예외가 발생한 프레임에서 디버거 시작
pdb.post_mortem(exc_traceback)
# 예외 재발생
raise
return wrapper
@debug_on_error
def problematic_function(x, y):
"""문제가 있는 함수"""
result = x / y # y가 0이면 오류
return result * 100
# 로깅을 활용한 디버깅
import logging
import sys
# 로거 설정
def setup_logger(name: str, level=logging.DEBUG) -> logging.Logger:
"""로거 설정"""
logger = logging.getLogger(name)
logger.setLevel(level)
# 핸들러 설정
console_handler = logging.StreamHandler(sys.stdout)
file_handler = logging.FileHandler('debug.log')
# 포맷터 설정
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
)
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
return logger
# 로깅 활용 예제
class DataProcessor:
"""데이터 처리기"""
def __init__(self):
self.logger = setup_logger(self.__class__.__name__)
def process_data(self, data: List[Dict]) -> List[Dict]:
"""데이터 처리"""
self.logger.info(f"데이터 처리 시작: {len(data)}개 항목")
processed = []
for i, item in enumerate(data):
self.logger.debug(f"항목 {i} 처리 중: {item}")
try:
# 데이터 검증
if not self._validate_item(item):
self.logger.warning(f"잘못된 항목 건너뛰기: {item}")
continue
# 데이터 변환
transformed = self._transform_item(item)
self.logger.debug(f"변환된 항목: {transformed}")
processed.append(transformed)
except Exception as e:
self.logger.error(f"항목 {i} 처리 중 오류: {e}", exc_info=True)
self.logger.info(f"데이터 처리 완료: {len(processed)}개 성공")
return processed
def _validate_item(self, item: Dict) -> bool:
"""항목 검증"""
required_fields = ['id', 'name', 'value']
for field in required_fields:
if field not in item:
self.logger.debug(f"필수 필드 누락: {field}")
return False
return True
def _transform_item(self, item: Dict) -> Dict:
"""항목 변환"""
return {
'id': item['id'],
'name': item['name'].upper(),
'value': item['value'] * 2,
'processed': True
}
고급 디버깅 기법
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
import traceback
import sys
import inspect
from contextlib import contextmanager
import time
# 실행 시간 측정
@contextmanager
def timer(name: str = "Operation"):
"""실행 시간 측정 컨텍스트 관리자"""
start = time.time()
print(f"{name} 시작...")
try:
yield
finally:
end = time.time()
print(f"{name} 완료: {end - start:.4f}초")
# 사용 예제
with timer("데이터 처리"):
# 시간이 걸리는 작업
time.sleep(1)
process_large_dataset()
# 메모리 프로파일링
import tracemalloc
def memory_profiling_example():
"""메모리 프로파일링 예제"""
# 메모리 추적 시작
tracemalloc.start()
# 메모리를 사용하는 작업
data = [i ** 2 for i in range(1000000)]
# 현재 메모리 사용량
current, peak = tracemalloc.get_traced_memory()
print(f"현재 메모리: {current / 10**6:.1f} MB")
print(f"최대 메모리: {peak / 10**6:.1f} MB")
# 메모리 추적 종료
tracemalloc.stop()
return data
# 스택 트레이스 분석
def analyze_stack():
"""스택 트레이스 분석"""
for frame_info in inspect.stack():
frame = frame_info[0]
filename = frame_info[1]
line_number = frame_info[2]
function_name = frame_info[3]
print(f"{filename}:{line_number} in {function_name}")
# 로컬 변수 출력
for var_name, var_value in frame.f_locals.items():
print(f" {var_name} = {var_value}")
# 커스텀 예외 처리
class DetailedException(Exception):
"""상세 정보를 포함한 예외"""
def __init__(self, message, **context):
super().__init__(message)
self.context = context
self.traceback = traceback.format_exc()
def __str__(self):
lines = [str(self.args[0])]
if self.context:
lines.append("\n컨텍스트:")
for key, value in self.context.items():
lines.append(f" {key}: {value}")
return '\n'.join(lines)
# 디버그 정보 수집
class DebugInfo:
"""디버그 정보 수집기"""
@staticmethod
def collect_system_info():
"""시스템 정보 수집"""
import platform
return {
'python_version': sys.version,
'platform': platform.platform(),
'machine': platform.machine(),
'processor': platform.processor()
}
@staticmethod
def collect_variables(frame=None):
"""변수 정보 수집"""
if frame is None:
frame = inspect.currentframe().f_back
return {
'locals': frame.f_locals.copy(),
'globals': {k: v for k, v in frame.f_globals.items()
if not k.startswith('__')}
}
@staticmethod
def create_debug_report(exception=None):
"""디버그 리포트 생성"""
report = {
'timestamp': datetime.now().isoformat(),
'system': DebugInfo.collect_system_info(),
'variables': DebugInfo.collect_variables(),
'stack_trace': traceback.format_stack()
}
if exception:
report['exception'] = {
'type': type(exception).__name__,
'message': str(exception),
'traceback': traceback.format_exc()
}
return report
# 조건부 디버깅
DEBUG = True
def debug_print(*args, **kwargs):
"""디버그 모드에서만 출력"""
if DEBUG:
caller = inspect.getframeinfo(inspect.currentframe().f_back)
print(f"[DEBUG {caller.filename}:{caller.lineno}]", *args, **kwargs)
# 어서션을 활용한 디버깅
def calculate_discount(price: float, discount_rate: float) -> float:
"""할인 가격 계산"""
assert price >= 0, f"가격은 0 이상이어야 합니다: {price}"
assert 0 <= discount_rate <= 1, f"할인율은 0과 1 사이여야 합니다: {discount_rate}"
discounted_price = price * (1 - discount_rate)
assert discounted_price >= 0, "할인된 가격이 음수입니다"
assert discounted_price <= price, "할인된 가격이 원가보다 큽니다"
return discounted_price
💡 실전 예제
1. 테스트 주도 개발 (TDD) 예제
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import pytest
from typing import List, Optional, Dict
from datetime import datetime, timedelta
# 1단계: 테스트 먼저 작성
class TestShoppingCart:
"""장바구니 테스트"""
def test_empty_cart(self):
"""빈 장바구니 테스트"""
cart = ShoppingCart()
assert cart.is_empty() is True
assert cart.total() == 0
assert len(cart.items) == 0
def test_add_item(self):
"""상품 추가 테스트"""
cart = ShoppingCart()
cart.add_item("Apple", 1.5, 3)
assert cart.is_empty() is False
assert len(cart.items) == 1
assert cart.items[0]['name'] == "Apple"
assert cart.items[0]['price'] == 1.5
assert cart.items[0]['quantity'] == 3
def test_remove_item(self):
"""상품 제거 테스트"""
cart = ShoppingCart()
cart.add_item("Apple", 1.5, 3)
cart.add_item("Banana", 0.8, 5)
cart.remove_item("Apple")
assert len(cart.items) == 1
assert cart.items[0]['name'] == "Banana"
def test_update_quantity(self):
"""수량 변경 테스트"""
cart = ShoppingCart()
cart.add_item("Apple", 1.5, 3)
cart.update_quantity("Apple", 5)
assert cart.items[0]['quantity'] == 5
def test_calculate_total(self):
"""합계 계산 테스트"""
cart = ShoppingCart()
cart.add_item("Apple", 1.5, 3) # 4.5
cart.add_item("Banana", 0.8, 5) # 4.0
cart.add_item("Orange", 2.0, 2) # 4.0
assert cart.total() == 12.5
def test_apply_discount(self):
"""할인 적용 테스트"""
cart = ShoppingCart()
cart.add_item("Apple", 10.0, 1)
cart.apply_discount(0.2) # 20% 할인
assert cart.total() == 8.0
def test_apply_coupon(self):
"""쿠폰 적용 테스트"""
cart = ShoppingCart()
cart.add_item("Apple", 10.0, 1)
# 유효한 쿠폰
valid_coupon = Coupon("SAVE10", 0.1, datetime.now() + timedelta(days=1))
cart.apply_coupon(valid_coupon)
assert cart.total() == 9.0
# 만료된 쿠폰
expired_coupon = Coupon("OLD10", 0.1, datetime.now() - timedelta(days=1))
with pytest.raises(ValueError, match="만료된 쿠폰"):
cart.apply_coupon(expired_coupon)
# 2단계: 테스트를 통과하는 코드 구현
class ShoppingCart:
"""장바구니 클래스"""
def __init__(self):
self.items: List[Dict] = []
self.discount_rate: float = 0.0
self.coupon: Optional['Coupon'] = None
def is_empty(self) -> bool:
"""장바구니가 비었는지 확인"""
return len(self.items) == 0
def add_item(self, name: str, price: float, quantity: int = 1):
"""상품 추가"""
# 이미 있는 상품인지 확인
for item in self.items:
if item['name'] == name:
item['quantity'] += quantity
return
# 새 상품 추가
self.items.append({
'name': name,
'price': price,
'quantity': quantity
})
def remove_item(self, name: str):
"""상품 제거"""
self.items = [item for item in self.items if item['name'] != name]
def update_quantity(self, name: str, quantity: int):
"""수량 변경"""
for item in self.items:
if item['name'] == name:
item['quantity'] = quantity
break
def subtotal(self) -> float:
"""할인 전 합계"""
return sum(item['price'] * item['quantity'] for item in self.items)
def total(self) -> float:
"""할인 후 합계"""
subtotal = self.subtotal()
# 일반 할인 적용
if self.discount_rate > 0:
subtotal *= (1 - self.discount_rate)
# 쿠폰 할인 적용
if self.coupon and self.coupon.is_valid():
subtotal *= (1 - self.coupon.discount_rate)
return round(subtotal, 2)
def apply_discount(self, rate: float):
"""할인율 적용"""
if not 0 <= rate <= 1:
raise ValueError("할인율은 0과 1 사이여야 합니다")
self.discount_rate = rate
def apply_coupon(self, coupon: 'Coupon'):
"""쿠폰 적용"""
if not coupon.is_valid():
raise ValueError("만료된 쿠폰입니다")
self.coupon = coupon
class Coupon:
"""쿠폰 클래스"""
def __init__(self, code: str, discount_rate: float, expires_at: datetime):
self.code = code
self.discount_rate = discount_rate
self.expires_at = expires_at
def is_valid(self) -> bool:
"""쿠폰 유효성 확인"""
return datetime.now() < self.expires_at
# 3단계: 리팩토링 (코드 개선)
class ImprovedShoppingCart(ShoppingCart):
"""개선된 장바구니"""
def __init__(self, max_items: int = 100):
super().__init__()
self.max_items = max_items
self.history: List[Dict] = []
def add_item(self, name: str, price: float, quantity: int = 1):
"""상품 추가 (개선)"""
if len(self.items) >= self.max_items:
raise ValueError(f"장바구니는 최대 {self.max_items}개까지 담을 수 있습니다")
if price < 0:
raise ValueError("가격은 0 이상이어야 합니다")
if quantity <= 0:
raise ValueError("수량은 1 이상이어야 합니다")
# 기록 저장
self.history.append({
'action': 'add',
'item': name,
'quantity': quantity,
'timestamp': datetime.now()
})
super().add_item(name, price, quantity)
def get_history(self) -> List[Dict]:
"""변경 기록 조회"""
return self.history.copy()
def save_to_json(self, filepath: str):
"""장바구니 저장"""
import json
data = {
'items': self.items,
'discount_rate': self.discount_rate,
'coupon': {
'code': self.coupon.code,
'discount_rate': self.coupon.discount_rate,
'expires_at': self.coupon.expires_at.isoformat()
} if self.coupon else None,
'saved_at': datetime.now().isoformat()
}
with open(filepath, 'w') as f:
json.dump(data, f, indent=2)
@classmethod
def load_from_json(cls, filepath: str) -> 'ImprovedShoppingCart':
"""장바구니 로드"""
import json
with open(filepath, 'r') as f:
data = json.load(f)
cart = cls()
cart.items = data['items']
cart.discount_rate = data['discount_rate']
if data['coupon']:
cart.coupon = Coupon(
data['coupon']['code'],
data['coupon']['discount_rate'],
datetime.fromisoformat(data['coupon']['expires_at'])
)
return cart
2. 통합 테스트와 E2E 테스트
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import pytest
import sqlite3
import tempfile
import os
from typing import List, Dict
# 애플리케이션 코드
class Task:
"""할일 모델"""
def __init__(self, id: int, title: str, description: str,
completed: bool = False, user_id: int = None):
self.id = id
self.title = title
self.description = description
self.completed = completed
self.user_id = user_id
class TaskRepository:
"""할일 저장소"""
def __init__(self, db_path: str):
self.db_path = db_path
self._init_db()
def _init_db(self):
"""데이터베이스 초기화"""
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT,
completed BOOLEAN DEFAULT 0,
user_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
def create(self, task: Task) -> int:
"""할일 생성"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("""
INSERT INTO tasks (title, description, completed, user_id)
VALUES (?, ?, ?, ?)
""", (task.title, task.description, task.completed, task.user_id))
return cursor.lastrowid
def get_by_id(self, task_id: int) -> Optional[Task]:
"""ID로 할일 조회"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.execute(
"SELECT * FROM tasks WHERE id = ?", (task_id,)
)
row = cursor.fetchone()
if row:
return Task(
id=row['id'],
title=row['title'],
description=row['description'],
completed=bool(row['completed']),
user_id=row['user_id']
)
return None
def get_by_user(self, user_id: int) -> List[Task]:
"""사용자별 할일 목록"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.execute(
"SELECT * FROM tasks WHERE user_id = ? ORDER BY created_at DESC",
(user_id,)
)
return [
Task(
id=row['id'],
title=row['title'],
description=row['description'],
completed=bool(row['completed']),
user_id=row['user_id']
)
for row in cursor.fetchall()
]
def update(self, task: Task) -> bool:
"""할일 수정"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("""
UPDATE tasks
SET title = ?, description = ?, completed = ?
WHERE id = ?
""", (task.title, task.description, task.completed, task.id))
return cursor.rowcount > 0
def delete(self, task_id: int) -> bool:
"""할일 삭제"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute(
"DELETE FROM tasks WHERE id = ?", (task_id,)
)
return cursor.rowcount > 0
class TaskService:
"""할일 서비스"""
def __init__(self, repository: TaskRepository):
self.repository = repository
def create_task(self, title: str, description: str, user_id: int) -> Task:
"""할일 생성"""
if not title:
raise ValueError("제목은 필수입니다")
task = Task(
id=None,
title=title,
description=description,
user_id=user_id
)
task_id = self.repository.create(task)
task.id = task_id
return task
def complete_task(self, task_id: int) -> bool:
"""할일 완료"""
task = self.repository.get_by_id(task_id)
if not task:
raise ValueError(f"할일 {task_id}를 찾을 수 없습니다")
task.completed = True
return self.repository.update(task)
def get_user_tasks(self, user_id: int, completed_only: bool = False) -> List[Task]:
"""사용자 할일 목록"""
tasks = self.repository.get_by_user(user_id)
if completed_only:
tasks = [t for t in tasks if t.completed]
return tasks
# 통합 테스트
class TestTaskIntegration:
"""할일 통합 테스트"""
@pytest.fixture
def db_path(self):
"""임시 데이터베이스 경로"""
fd, path = tempfile.mkstemp(suffix='.db')
os.close(fd)
yield path
os.unlink(path)
@pytest.fixture
def repository(self, db_path):
"""저장소 fixture"""
return TaskRepository(db_path)
@pytest.fixture
def service(self, repository):
"""서비스 fixture"""
return TaskService(repository)
def test_create_and_retrieve_task(self, service):
"""할일 생성 및 조회 통합 테스트"""
# 할일 생성
task = service.create_task(
title="통합 테스트",
description="통합 테스트 설명",
user_id=1
)
assert task.id is not None
assert task.title == "통합 테스트"
assert task.completed is False
# 할일 조회
tasks = service.get_user_tasks(1)
assert len(tasks) == 1
assert tasks[0].title == "통합 테스트"
def test_complete_task_workflow(self, service):
"""할일 완료 워크플로우 테스트"""
# 1. 할일 생성
task = service.create_task("테스트 할일", "설명", user_id=1)
# 2. 할일 완료
success = service.complete_task(task.id)
assert success is True
# 3. 완료된 할일 확인
completed_tasks = service.get_user_tasks(1, completed_only=True)
assert len(completed_tasks) == 1
assert completed_tasks[0].completed is True
def test_multiple_users_isolation(self, service):
"""여러 사용자 간 격리 테스트"""
# 사용자 1의 할일
service.create_task("User 1 Task 1", "", user_id=1)
service.create_task("User 1 Task 2", "", user_id=1)
# 사용자 2의 할일
service.create_task("User 2 Task 1", "", user_id=2)
# 각 사용자의 할일 확인
user1_tasks = service.get_user_tasks(1)
user2_tasks = service.get_user_tasks(2)
assert len(user1_tasks) == 2
assert len(user2_tasks) == 1
# 다른 사용자의 할일에 접근 불가
assert all(t.user_id == 1 for t in user1_tasks)
assert all(t.user_id == 2 for t in user2_tasks)
@pytest.mark.parametrize("num_tasks", [10, 50, 100])
def test_performance_with_many_tasks(self, service, num_tasks):
"""많은 할일 처리 성능 테스트"""
import time
# 할일 생성
start_time = time.time()
for i in range(num_tasks):
service.create_task(
title=f"Task {i}",
description=f"Description {i}",
user_id=1
)
creation_time = time.time() - start_time
# 할일 조회
start_time = time.time()
tasks = service.get_user_tasks(1)
query_time = time.time() - start_time
assert len(tasks) == num_tasks
assert creation_time < num_tasks * 0.01 # 할일당 10ms 이하
assert query_time < 0.1 # 조회는 100ms 이하
print(f"\n{num_tasks}개 할일:")
print(f" 생성 시간: {creation_time:.3f}초")
print(f" 조회 시간: {query_time:.3f}초")
# E2E 테스트 (웹 애플리케이션 예제)
from flask import Flask, request, jsonify
app = Flask(__name__)
task_service = None # 실제로는 의존성 주입
@app.route('/api/tasks', methods=['POST'])
def create_task():
"""할일 생성 API"""
data = request.get_json()
try:
task = task_service.create_task(
title=data['title'],
description=data.get('description', ''),
user_id=data['user_id']
)
return jsonify({
'id': task.id,
'title': task.title,
'description': task.description,
'completed': task.completed
}), 201
except ValueError as e:
return jsonify({'error': str(e)}), 400
@app.route('/api/tasks/<int:task_id>/complete', methods=['PUT'])
def complete_task(task_id):
"""할일 완료 API"""
try:
success = task_service.complete_task(task_id)
return jsonify({'success': success}), 200
except ValueError as e:
return jsonify({'error': str(e)}), 404
# E2E 테스트
@pytest.fixture
def client():
"""Flask 테스트 클라이언트"""
global task_service
# 테스트용 설정
app.config['TESTING'] = True
with tempfile.NamedTemporaryFile(suffix='.db') as f:
repository = TaskRepository(f.name)
task_service = TaskService(repository)
with app.test_client() as client:
yield client
def test_api_create_task(client):
"""API를 통한 할일 생성 E2E 테스트"""
# API 요청
response = client.post('/api/tasks', json={
'title': 'E2E 테스트 할일',
'description': 'API를 통한 생성',
'user_id': 1
})
# 응답 확인
assert response.status_code == 201
data = response.get_json()
assert data['title'] == 'E2E 테스트 할일'
assert 'id' in data
# 생성된 할일 완료
task_id = data['id']
response = client.put(f'/api/tasks/{task_id}/complete')
assert response.status_code == 200
assert response.get_json()['success'] is True
def test_api_error_handling(client):
"""API 오류 처리 E2E 테스트"""
# 잘못된 요청
response = client.post('/api/tasks', json={
'description': '제목 없음',
'user_id': 1
})
assert response.status_code == 400
assert 'error' in response.get_json()
# 존재하지 않는 할일
response = client.put('/api/tasks/999/complete')
assert response.status_code == 404
assert 'error' in response.get_json()
⚠️ 초보자들이 자주 하는 실수
1. 테스트 코드를 작성하지 않는 실수
1
2
3
4
5
6
7
8
9
10
11
12
# ❌ 잘못된 방법: 테스트 없이 개발
def calculate_discount(price, rate):
return price * rate # 버그: 할인이 아니라 곱셈!
# ✅ 올바른 방법: 테스트와 함께 개발
def calculate_discount(price, rate):
"""할인 가격 계산"""
return price * (1 - rate)
def test_calculate_discount():
assert calculate_discount(10000, 0.1) == 9000
assert calculate_discount(5000, 0.2) == 4000
2. 예외 상황을 테스트하지 않는 실수
1
2
3
4
5
6
7
8
9
# ❌ 잘못된 방법: 정상 케이스만 테스트
def test_divide_only_normal():
assert divide(10, 2) == 5
# ✅ 올바른 방법: 예외 상황도 테스트
def test_divide_comprehensive():
assert divide(10, 2) == 5
with pytest.raises(ZeroDivisionError):
divide(10, 0)
3. print문으로만 디버깅하는 실수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# ❌ 잘못된 방법: print문 남발
def process_data(data):
print(f"데이터: {data}") # 임시 디버깅 코드
result = data * 2
print(f"결과: {result}") # 프로덕션에 남김
return result
# ✅ 올바른 방법: 로깅 시스템 활용
import logging
logger = logging.getLogger(__name__)
def process_data(data):
logger.debug(f"처리할 데이터: {data}")
result = data * 2
logger.info(f"처리 완료: {result}")
return result
4. 테스트 데이터베이스를 사용하지 않는 실수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ❌ 잘못된 방법: 실제 DB 사용
def test_user_creation():
user = create_user("test@example.com") # 실제 DB에 저장!
assert user.email == "test@example.com"
# ✅ 올바른 방법: 테스트 DB 또는 모킹
@pytest.fixture
def test_db():
db = create_test_database()
yield db
db.cleanup()
def test_user_creation(test_db):
user = create_user("test@example.com", db=test_db)
assert user.email == "test@example.com"
5. 테스트 간 의존성을 만드는 실수
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
# ❌ 잘못된 방법: 테스트 간 의존성
class TestUserService:
def test_create_user(self):
self.user = create_user("test@example.com")
assert self.user.id == 1
def test_update_user(self):
# 이전 테스트에 의존!
self.user.name = "Updated"
update_user(self.user)
assert self.user.name == "Updated"
# ✅ 올바른 방법: 독립적인 테스트
class TestUserService:
@pytest.fixture
def user(self):
return create_user("test@example.com")
def test_create_user(self):
user = create_user("test@example.com")
assert user.email == "test@example.com"
def test_update_user(self, user):
user.name = "Updated"
update_user(user)
assert user.name == "Updated"
6. 테스트 커버리지만 신경 쓰는 실수
1
2
3
4
5
6
7
8
9
10
11
# ❌ 잘못된 방법: 커버리지만 높이기
def test_meaningless():
func() # 단순히 함수만 호출
# assert 없음!
# ✅ 올바른 방법: 의미 있는 테스트
def test_func_behavior():
result = func()
assert result.status == 'success'
assert len(result.data) > 0
assert result.timestamp is not None
7. 프로덕션 코드에 디버깅 코드 남기는 실수
1
2
3
4
5
6
7
8
9
10
11
# ❌ 잘못된 방법: 디버깅 코드 방치
def important_function():
import pdb; pdb.set_trace() # 프로덕션에 남김!
# breakpoint() # Python 3.7+ 방식도 마찬가지
return "result"
# ✅ 올바른 방법: 조건부 디버깅
def important_function():
if os.environ.get('DEBUG') == 'true':
import pdb; pdb.set_trace()
return "result"
8. 에러 메시지를 무시하는 실수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# ❌ 잘못된 방법: 에러 숨기기
try:
result = risky_operation()
except:
pass # 모든 에러를 무시!
# ✅ 올바른 방법: 적절한 예외 처리
try:
result = risky_operation()
except SpecificError as e:
logger.error(f"특정 오류 발생: {e}")
raise
except Exception as e:
logger.error(f"예상치 못한 오류: {e}")
# 적절한 복구 로직
result = default_value
🎯 핵심 정리
테스트 전략
graph TD
A[테스트 피라미드] --> B[단위 테스트<br/>70%]
A --> C[통합 테스트<br/>20%]
A --> D[E2E 테스트<br/>10%]
B --> E[빠름, 격리됨]
C --> F[중간 속도, 상호작용]
D --> G[느림, 실제 환경]
디버깅 Best Practices
- 로깅 활용: 적절한 로그 레벨 사용
- 작은 단위로 테스트: 문제 범위 축소
- 재현 가능한 테스트: 일관된 환경 구성
- 도구 활용: pdb, IDE 디버거, 프로파일러
- 예외 처리: 명확한 오류 메시지
🎓 파이썬 마스터하기 시리즈
📚 기초편 (1-7)
- Python 소개와 개발 환경 설정
- 변수, 자료형, 연산자 완벽 정리
- 조건문과 반복문 마스터하기
- 함수와 람다 완벽 가이드
- 리스트, 튜플, 딕셔너리 정복하기
- 문자열 처리와 정규표현식
- 파일 입출력과 예외 처리
🚀 중급편 (8-12)
💼 고급편 (13-16)
- 웹 스크래핑과 API 개발
- 테스트와 디버깅 전략 (현재 글)
- 성능 최적화 기법
- 멀티프로세싱과 병렬 처리
이전글: 웹 스크래핑과 API 개발 ⬅️ 현재글: 테스트와 디버깅 전략 다음글: 성능 최적화 기법 ➡️
이번 포스트에서는 Python의 테스트와 디버깅 전략을 완벽히 마스터했습니다. 다음 포스트에서는 성능 최적화 기법에 대해 자세히 알아보겠습니다. Happy Coding! 🐍✨