ทดสอบการสร้าง QR Code: Unit Test และ Integration Test
Testing strategies for QR code generators: output validation, round-trip testing, visual regression, and edge cases.
Testing QR Code Generation: Unit and Integration Tests
Robust testing ensures your QR code generation produces valid, scannable codes under all input conditions.
Unit Tests
Round-trip testing: The most fundamental test — generate a QR code and decode it, verifying the output matches the input:
import segno
import io
from pyzbar.pyzbar import decode
from PIL import Image
def test_round_trip():
data = "https://example.com/test"
qr = segno.make(data, error="m")
buffer = io.BytesIO()
qr.save(buffer, kind="png", scale=10)
buffer.seek(0)
image = Image.open(buffer)
results = decode(image)
assert len(results) == 1
assert results[0].data.decode("utf-8") == data
Encoding mode verification: Verify the library selects the expected encoding mode:
def test_numeric_mode():
qr = segno.make("1234567890")
assert qr.mode == "numeric"
def test_alphanumeric_mode():
qr = segno.make("HTTPS://EXAMPLE.COM")
# Verify version is lower than byte mode would require
Edge Case Tests
Test boundary conditions:
- Empty string: Should the library raise an error or generate a valid code?
- Maximum capacity: Data that exactly fills a version's capacity
- Special characters: Unicode, emoji, control characters
- Very long URLs: Data requiring Version 30+
- All encoding modes: Numeric, alphanumeric, byte, kanji
Integration Tests
Multi-scanner validation: Decode generated QR codes with multiple reader libraries:
def test_multi_scanner(qr_image):
# Test with pyzbar
pyzbar_result = pyzbar_decode(qr_image)
# Test with OpenCV
opencv_result = opencv_decode(qr_image)
# Both should produce identical results
assert pyzbar_result == opencv_result
Print simulation: Test with simulated print degradation (add noise, reduce contrast, blur edges).
Visual Regression Testing
For custom-styled QR codes, compare generated images against known-good reference images:
- Pixel-difference comparison with tolerance threshold
- Perceptual hash comparison for layout changes
- Automated scanning to verify functional equivalence
Key Takeaways
- Round-trip testing (generate then decode) is the essential baseline test
- Test all encoding modes, edge cases, and capacity boundaries
- Multi-scanner validation ensures broad compatibility
- Visual regression catches unintended design changes
- Simulate print degradation for production-readiness testing