Lecture 27: Skill Testing and Quality Assurance

Master Skill testing methods and quality assurance techniques to ensure stable and reliable operation.

一、Testing Strategy

1.1 Testing Pyramid

1
2
3
4
5
6
7
8
9
10
        /\
/ \ E2E Testing (End-to-End)
/____\ Few, critical paths only
/ \
/ /\\\ \ Integration Testing
/ / \\ \ Moderate quantity
/___/____\___\
/ \
/ /\ /\ /\ /\ \ Unit Testing
\/ \/ \/ Large quantity, fast

1.2 Testing Types

Test TypePurposeTools
Unit TestingVerify individual function correctnesspytest
Integration TestingVerify module collaborationpytest
End-to-End TestingVerify complete workflowsManual/Automated
Performance TestingVerify response speedlocust
Security TestingDiscover security vulnerabilitiesbandit

二、Unit Testing

2.1 Testing Framework

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
# tests/test_invoice.py
import pytest
from unittest.mock import Mock, patch
from services.invoice_service import InvoiceService

class TestInvoiceService:
"""Invoice Service Tests"""

@pytest.fixture
def service(self):
"""Test fixture"""
mock_ocr = Mock()
mock_db = Mock()
return InvoiceService(mock_ocr, mock_db)

def test_extract_invoice_code(self, service):
"""Test invoice code extraction"""
text = "Invoice Code: 123456789012"
result = service._extract_pattern(text, r'Invoice Code[::]\s*(\d{12})')
assert result == '123456789012'

def test_extract_invoice_code_not_found(self, service):
"""Test invoice code not found"""
text = "This is plain text"
result = service._extract_pattern(text, r'Invoice Code[::]\s*(\d{12})')
assert result is None

def test_validate_invoice_success(self, service):
"""Test invoice validation success"""
info = {
'invoice_code': '123456789012',
'invoice_number': '12345678',
'amount': '1000.00'
}
service.db.check_duplicate.return_value = False

result = service._validate_invoice(info)

assert result['is_valid'] is True
assert len(result['errors']) == 0

def test_validate_invoice_duplicate(self, service):
"""Test duplicate invoice"""
info = {
'invoice_code': '123456789012',
'invoice_number': '12345678',
'amount': '1000.00'
}
service.db.check_duplicate.return_value = True

result = service._validate_invoice(info)

assert result['is_valid'] is False
assert 'Invoice already exists' in result['errors']

2.2 Mock Testing

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
# tests/test_with_mock.py
from unittest.mock import Mock, patch, MagicMock

class TestWithMock:
"""Mock Testing Examples"""

def test_mock_function(self):
"""Mock function"""
mock_func = Mock(return_value=42)
result = mock_func()

assert result == 42
mock_func.assert_called_once()

def test_patch_decorator(self):
"""Using patch decorator"""
with patch('services.invoice_service.OCRService') as mock_ocr:
mock_instance = MagicMock()
mock_instance.recognize.return_value = "Recognition result"
mock_ocr.return_value = mock_instance

# Execute test
from services.invoice_service import InvoiceService
service = InvoiceService(mock_instance, Mock())
result = service.ocr.recognize("test.jpg")

assert result == "Recognition result"

@patch('services.invoice_service.requests.get')
def test_api_call(self, mock_get):
"""Test API call"""
mock_get.return_value.json.return_value = {'status': 'ok'}

# Execute API call
import requests
response = requests.get('http://api.example.com')

assert response.json()['status'] == 'ok'

三、Integration Testing

3.1 Test Database

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
# tests/test_integration.py
import pytest
import sqlite3
from services.invoice_service import InvoiceService

class TestIntegration:
"""Integration Tests"""

@pytest.fixture(scope='function')
def db(self):
"""Create test database"""
conn = sqlite3.connect(':memory:')
conn.execute('''
CREATE TABLE invoices (
id INTEGER PRIMARY KEY,
invoice_code TEXT,
invoice_number TEXT,
amount REAL
)
''')
yield conn
conn.close()

def test_save_and_query_invoice(self, db):
"""Test save and query invoice"""
# Save invoice
db.execute('''
INSERT INTO invoices (invoice_code, invoice_number, amount)
VALUES (?, ?, ?)
''', ('123456789012', '12345678', 1000.00))
db.commit()

# Query invoice
cursor = db.execute('SELECT * FROM invoices WHERE invoice_code = ?',
('123456789012',))
result = cursor.fetchone()

assert result[1] == '123456789012'
assert result[3] == 1000.00

四、End-to-End Testing

4.1 Conversation Flow Testing

# tests/test_e2e.py
class TestEndToEnd:
    """End-to-End Tests"""

    def test_invoice_recognition_flow(self):
        """Test complete invoice recognition workflow"""


## 🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 **AI 编程实战课** 帮你从零上手!

- 👉 **课程报名**:[点击这里报名,前3讲免费试听](https://r7up9.xetslk.com/s/1uP5YW)
- 👉 **免费试看**:[B站免费试看前3讲,先看看适不适合自己](https://www.bilibili.com/cheese/play/ss982042944)