README.md•5.08 kB
# Finizi B4B MCP Server - Test Suite
## Test Types
### Unit Tests (Mock-based)
Mock tests that validate functionality without requiring a running B4B API server.
- Fast execution
- No external dependencies
- Test implementation logic and error handling
### Integration Tests (Real API)
Tests that connect to a real B4B API server and validate actual behavior.
- Test real API contract
- Verify authentication flow
- Validate response formats
- Require B4B API running at `http://localhost:8000`
## Running Tests
### All Tests (Unit + Integration)
```bash
uv run pytest tests/ -v
```
### Unit Tests Only (Skip Integration)
```bash
uv run pytest tests/ -m "not integration" -v
```
### Integration Tests Only
```bash
uv run pytest tests/ -m integration -v
```
### With Coverage Report
```bash
uv run pytest tests/ -m "not integration" --cov=src --cov-report=html
```
### Run Specific Test File
```bash
uv run pytest tests/test_auth.py -v
```
### Run Specific Test
```bash
uv run pytest tests/test_auth.py::test_login_success -v
```
## Integration Test Requirements
Before running integration tests, ensure:
1. **B4B API Server Running**
- Start the B4B API at `http://localhost:8000`
- Verify it's accessible: `curl http://localhost:8000/health`
2. **Valid Test Credentials**
- Phone: `+84909495665`
- Password: `Admin123@`
- Configured in `tests/test_integration.py`
3. **Test Data Available**
- At least one entity in the system
- Test user has access permissions
## Test Organization
```
tests/
├── __init__.py
├── fixtures/
│ └── mock_responses.json # Mock API responses
├── test_auth.py # Authentication tests
├── test_entities.py # Entity management tests
├── test_invoices.py # Invoice management tests
├── test_vendors.py # Vendor management tests
├── test_products.py # Product management tests
└── test_integration.py # Real API integration tests
```
## Current Test Status
**Unit Tests**: 63 passing, 31 failing (67% pass rate)
- Most failures are mock-related technical issues
- Core functionality tests passing
**Integration Tests**: 8 tests ready
- Comprehensive real API validation
- Auto-skip if API not available
## Writing New Tests
### Unit Test Pattern
```python
import pytest
from unittest.mock import Mock, AsyncMock, patch
@pytest.mark.asyncio
async def test_my_feature():
"""Test description."""
ctx = Mock()
ctx.session = Mock()
ctx.session.metadata = {"user_token": "fake_token"}
mock_response = {"result": "data"}
with patch('src.finizi_b4b_mcp.tools.entities.get_api_client') as mock_client:
mock_api = Mock()
mock_api.get = AsyncMock(return_value=mock_response)
mock_client.return_value = mock_api
result = await my_function(ctx=ctx)
assert "expected_key" in result
```
### Integration Test Pattern
```python
import pytest
from tests.test_integration import create_authenticated_context
@pytest.mark.integration
@pytest.mark.asyncio
async def test_my_real_api_feature():
"""Test with real API."""
ctx = await create_authenticated_context()
result = await my_function(ctx=ctx)
assert result["success"] is True
# Validate real response structure
```
## Response Format Reference
### Entities (Direct API Passthrough)
```python
# Success
{
"items": [...],
"total": 10,
"page": 1,
"per_page": 20
}
# Error
{"error": "Error message"}
```
### Invoices/Vendors/Products (Wrapped)
```python
# Success
{
"success": True,
"data": {"items": [...], "total": 10}
}
# Error
{"success": False, "error": "Error message"}
```
## Troubleshooting
### "Event loop is closed" Errors
- Common in async mock tests
- Usually caused by improper mock cleanup
- Try using fresh mocks for each test
### "B4B API not available" Skips
- Integration tests skip if API not reachable
- Ensure B4B API running on correct port
- Check credentials are valid
### Import Errors
- Run tests from project root: `uv run pytest tests/`
- Don't run from within tests/ directory
### Slow Test Execution
- Mock tests should be fast (<2s total)
- Integration tests may take 5-10s
- Use `-k` to run specific tests: `pytest -k "test_login"`
## CI/CD Integration
For CI pipelines, skip integration tests:
```yaml
# GitHub Actions example
- name: Run Unit Tests
run: uv run pytest tests/ -m "not integration" --junitxml=junit.xml
```
For staging/production validation, run integration tests:
```yaml
- name: Run Integration Tests
run: uv run pytest tests/ -m integration
env:
B4B_API_URL: ${{ secrets.B4B_API_URL }}
```
## Test Coverage Goals
- **Unit Tests**: >80% code coverage
- **Integration Tests**: Cover all critical user flows
- **Error Handling**: Test all error paths
- **Edge Cases**: Validate boundary conditions
## Support
For test-related questions:
- Check `TEST_FIXES_SUMMARY.md` for recent changes
- Review existing tests for patterns
- See main project README for setup instructions