mathiassandnes Claude Opus 4.5 commited on
Commit
85fcbc2
·
1 Parent(s): b51241a

Add test suite, CI/CD, and development workflow

Browse files

Test Suite (37 tests):
- test_config.py: Config structure and validation
- test_calculations.py: Core business math (EoLRR, circular vs linear)
- test_app.py: Smoke tests for imports and config loading

GitHub Actions:
- test.yml: Run tests on push to dev/main and PRs
- deploy-hf.yml: Manual-only deploy to HF Space

Claude Skills:
- /run-tests: Run pytest locally
- /deploy-hf: Deploy to HF Space
- /create-pr: Create PR from dev to main
- /setup-branch: Configure dev branch

Branch Strategy:
- dev: All development
- main: Stable releases via PR
- HF deploy: Manual only from main

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

.claude/skills/create-pr.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Create Pull Request
2
+
3
+ Create a PR from dev to main branch.
4
+
5
+ ## Usage
6
+
7
+ ```
8
+ /create-pr
9
+ ```
10
+
11
+ ## Instructions
12
+
13
+ 1. **Ensure you're on dev branch with latest changes:**
14
+ ```bash
15
+ git checkout dev
16
+ git status # Check for uncommitted changes
17
+ ```
18
+
19
+ 2. **Run tests:**
20
+ ```bash
21
+ pytest tests/ -v
22
+ ```
23
+ All tests must pass before creating PR.
24
+
25
+ 3. **Push dev branch:**
26
+ ```bash
27
+ git push origin dev
28
+ ```
29
+
30
+ 4. **Create PR using GitHub CLI:**
31
+ ```bash
32
+ gh pr create --base main --head dev --title "Merge dev to main" --body "## Summary
33
+ - [List changes here]
34
+
35
+ ## Test Results
36
+ All tests passing locally.
37
+
38
+ ## Checklist
39
+ - [ ] Tests pass
40
+ - [ ] No breaking changes
41
+ - [ ] Ready for HF deployment"
42
+ ```
43
+
44
+ 5. **Wait for CI:**
45
+ - GitHub Actions will run tests on the PR
46
+ - Review any failures before merging
47
+
48
+ ## Alternative: GitHub Web UI
49
+
50
+ 1. Go to https://github.com/Liis-com/simulator
51
+ 2. Click "Pull requests" → "New pull request"
52
+ 3. Set base: `main`, compare: `dev`
53
+ 4. Add title and description
54
+ 5. Create PR
55
+
56
+ ## After Merge
57
+
58
+ The main branch is updated. To deploy to HF Space, use `/deploy-hf`.
.claude/skills/deploy-hf.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deploy to HF Space
2
+
3
+ Deploy the simulator to Hugging Face Space.
4
+
5
+ ## Usage
6
+
7
+ ```
8
+ /deploy-hf
9
+ ```
10
+
11
+ ## Instructions
12
+
13
+ 1. **Ensure you're on main branch:**
14
+ ```bash
15
+ git checkout main
16
+ ```
17
+
18
+ 2. **Verify all tests pass:**
19
+ ```bash
20
+ pytest tests/ -v
21
+ ```
22
+
23
+ 3. **Push to HF Space:**
24
+ ```bash
25
+ git push hf main --force
26
+ ```
27
+
28
+ If `hf` remote not configured:
29
+ ```bash
30
+ git remote add hf https://huggingface.co/spaces/Liisdotcom/simulator
31
+ ```
32
+
33
+ ## Prerequisites
34
+
35
+ - Must be on `main` branch (not `dev`)
36
+ - All tests must pass
37
+ - HF remote must be configured with write access
38
+
39
+ ## Via GitHub Actions (Recommended)
40
+
41
+ 1. Go to GitHub repo → Actions → "Deploy to HF Space"
42
+ 2. Click "Run workflow"
43
+ 3. Type "deploy" to confirm
44
+ 4. Wait for deployment to complete
45
+
46
+ This method:
47
+ - Runs tests before deploying
48
+ - Uses stored HF_TOKEN secret
49
+ - Creates deployment summary
50
+
51
+ ## After Deployment
52
+
53
+ Verify at: https://huggingface.co/spaces/Liisdotcom/simulator
54
+
55
+ The Space will rebuild automatically (1-2 minutes).
.claude/skills/run-tests.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run Tests
2
+
3
+ Run the test suite to verify changes before committing.
4
+
5
+ ## Usage
6
+
7
+ ```
8
+ /run-tests
9
+ ```
10
+
11
+ ## Instructions
12
+
13
+ 1. **Run the full test suite:**
14
+ ```bash
15
+ cd /Users/mathi/CursorProjects/Liis.com\ -\ Simulator/simulator
16
+ pytest tests/ -v
17
+ ```
18
+
19
+ 2. **If tests fail:**
20
+ - Review the error output
21
+ - Fix the failing tests or the code they're testing
22
+ - Re-run until all tests pass
23
+
24
+ 3. **Run specific test files:**
25
+ ```bash
26
+ pytest tests/test_config.py -v # Config validation
27
+ pytest tests/test_calculations.py -v # Core math
28
+ pytest tests/test_app.py -v # App smoke tests
29
+ ```
30
+
31
+ 4. **Run with coverage (optional):**
32
+ ```bash
33
+ pip install pytest-cov
34
+ pytest tests/ -v --cov=. --cov-report=term-missing
35
+ ```
36
+
37
+ ## Test Categories
38
+
39
+ | File | Tests |
40
+ |------|-------|
41
+ | `test_config.py` | Config structure, required fields, value ranges |
42
+ | `test_calculations.py` | EoLRR, circular vs linear profit, fleet economics |
43
+ | `test_app.py` | Imports, config loading, product details |
44
+
45
+ ## Before Committing
46
+
47
+ All tests must pass before:
48
+ - Committing to dev branch
49
+ - Creating a PR to main
50
+ - Deploying to HF Space
.claude/skills/setup-branch.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Setup Branch
2
+
3
+ Create and configure the dev branch for development.
4
+
5
+ ## Usage
6
+
7
+ ```
8
+ /setup-branch
9
+ ```
10
+
11
+ ## Instructions
12
+
13
+ ### Initial Setup (One Time)
14
+
15
+ 1. **Create dev branch from main:**
16
+ ```bash
17
+ git checkout main
18
+ git pull origin main
19
+ git checkout -b dev
20
+ git push -u origin dev
21
+ ```
22
+
23
+ 2. **Verify branch exists:**
24
+ ```bash
25
+ git branch -a
26
+ ```
27
+
28
+ ### Daily Workflow
29
+
30
+ 1. **Start work on dev:**
31
+ ```bash
32
+ git checkout dev
33
+ git pull origin dev # Get latest changes
34
+ ```
35
+
36
+ 2. **Make changes and commit:**
37
+ ```bash
38
+ git add .
39
+ git commit -m "Description of changes"
40
+ ```
41
+
42
+ 3. **Push to dev:**
43
+ ```bash
44
+ git push origin dev
45
+ ```
46
+
47
+ 4. **When ready for release:**
48
+ - Use `/create-pr` to merge dev → main
49
+ - After merge, use `/deploy-hf` to deploy
50
+
51
+ ### Branch Strategy
52
+
53
+ ```
54
+ main ──────●────────●────────●────── (stable, deployable)
55
+ ↑ ↑ ↑
56
+ dev ●──●──●──●──●──●──●──●──●──●── (development)
57
+ ```
58
+
59
+ - **dev**: All development happens here
60
+ - **main**: Stable releases only (via PR)
61
+ - **HF Space**: Manual deploy from main only
62
+
63
+ ### Syncing Branches
64
+
65
+ If main has changes not in dev:
66
+ ```bash
67
+ git checkout dev
68
+ git merge main
69
+ git push origin dev
70
+ ```
.github/workflows/deploy-hf.yml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Deploy to HF Space
2
+
3
+ on:
4
+ workflow_dispatch: # Manual trigger only
5
+ inputs:
6
+ confirm:
7
+ description: 'Type "deploy" to confirm deployment'
8
+ required: true
9
+ default: ''
10
+
11
+ jobs:
12
+ deploy:
13
+ runs-on: ubuntu-latest
14
+ if: github.event.inputs.confirm == 'deploy'
15
+
16
+ steps:
17
+ - name: Checkout code
18
+ uses: actions/checkout@v4
19
+ with:
20
+ fetch-depth: 0 # Full history for push
21
+
22
+ - name: Set up Python
23
+ uses: actions/setup-python@v5
24
+ with:
25
+ python-version: '3.11'
26
+ cache: 'pip'
27
+
28
+ - name: Install dependencies
29
+ run: |
30
+ python -m pip install --upgrade pip
31
+ pip install -r requirements.txt
32
+
33
+ - name: Run tests before deploy
34
+ run: pytest tests/ -v --tb=short
35
+
36
+ - name: Deploy to Hugging Face Space
37
+ env:
38
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
39
+ run: |
40
+ git remote add hf https://user:${HF_TOKEN}@huggingface.co/spaces/Liisdotcom/simulator || true
41
+ git push hf main --force
42
+
43
+ - name: Deployment summary
44
+ run: |
45
+ echo "## Deployment Complete" >> $GITHUB_STEP_SUMMARY
46
+ echo "Deployed to: https://huggingface.co/spaces/Liisdotcom/simulator" >> $GITHUB_STEP_SUMMARY
.github/workflows/test.yml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Tests
2
+
3
+ on:
4
+ push:
5
+ branches: [dev, main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - name: Checkout code
15
+ uses: actions/checkout@v4
16
+
17
+ - name: Set up Python
18
+ uses: actions/setup-python@v5
19
+ with:
20
+ python-version: '3.11'
21
+ cache: 'pip'
22
+
23
+ - name: Install dependencies
24
+ run: |
25
+ python -m pip install --upgrade pip
26
+ pip install -r requirements.txt
27
+
28
+ - name: Run tests
29
+ run: pytest tests/ -v --tb=short
30
+
31
+ - name: Test summary
32
+ if: always()
33
+ run: |
34
+ echo "## Test Results" >> $GITHUB_STEP_SUMMARY
35
+ echo "Tests completed. Check output above for details." >> $GITHUB_STEP_SUMMARY
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .pytest_cache/
requirements.txt CHANGED
@@ -2,3 +2,4 @@ streamlit>=1.28.0
2
  plotly>=5.18.0
3
  pandas>=2.0.0
4
  pyyaml>=6.0
 
 
2
  plotly>=5.18.0
3
  pandas>=2.0.0
4
  pyyaml>=6.0
5
+ pytest>=7.0.0
tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # LiiS Simulator Test Suite
tests/conftest.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pytest fixtures for LiiS Simulator tests."""
2
+
3
+ import pytest
4
+ from pathlib import Path
5
+ import yaml
6
+
7
+
8
+ @pytest.fixture
9
+ def products_dir():
10
+ """Return path to products directory."""
11
+ return Path(__file__).parent.parent / "products"
12
+
13
+
14
+ @pytest.fixture
15
+ def besafe_config(products_dir):
16
+ """Load BeSafe product configuration."""
17
+ config_path = products_dir / "besafe" / "config.yaml"
18
+ return yaml.safe_load(config_path.read_text())
19
+
20
+
21
+ @pytest.fixture
22
+ def hamax_config(products_dir):
23
+ """Load Hamax product configuration."""
24
+ config_path = products_dir / "hamax" / "config.yaml"
25
+ return yaml.safe_load(config_path.read_text())
26
+
27
+
28
+ @pytest.fixture
29
+ def all_configs(products_dir):
30
+ """Load all product configurations."""
31
+ configs = {}
32
+ for product_dir in products_dir.iterdir():
33
+ if product_dir.is_dir():
34
+ config_path = product_dir / "config.yaml"
35
+ if config_path.exists():
36
+ configs[product_dir.name] = yaml.safe_load(config_path.read_text())
37
+ return configs
tests/test_app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Smoke tests for the Streamlit app."""
2
+
3
+ import pytest
4
+ from pathlib import Path
5
+ import sys
6
+
7
+
8
+ class TestAppImports:
9
+ """Test that app can be imported without errors."""
10
+
11
+ def test_yaml_importable(self):
12
+ """YAML library is available."""
13
+ import yaml
14
+ assert yaml is not None
15
+
16
+ def test_pandas_importable(self):
17
+ """Pandas is available."""
18
+ import pandas as pd
19
+ assert pd is not None
20
+
21
+ def test_plotly_importable(self):
22
+ """Plotly is available."""
23
+ import plotly.graph_objects as go
24
+ assert go is not None
25
+
26
+
27
+ class TestConfigLoading:
28
+ """Test that product configs can be loaded."""
29
+
30
+ def test_products_directory_exists(self, products_dir):
31
+ """Products directory exists."""
32
+ assert products_dir.exists()
33
+ assert products_dir.is_dir()
34
+
35
+ def test_at_least_one_product(self, all_configs):
36
+ """At least one product config exists."""
37
+ assert len(all_configs) > 0
38
+
39
+ def test_besafe_config_loadable(self, besafe_config):
40
+ """BeSafe config loads successfully."""
41
+ assert besafe_config is not None
42
+ assert "product" in besafe_config
43
+
44
+ def test_hamax_config_loadable(self, hamax_config):
45
+ """Hamax config loads successfully."""
46
+ assert hamax_config is not None
47
+ assert "product" in hamax_config
48
+
49
+
50
+ class TestProductDetails:
51
+ """Test product-specific details are correct."""
52
+
53
+ def test_besafe_is_car_seat(self, besafe_config):
54
+ """BeSafe is categorized as car seat."""
55
+ assert besafe_config["product"]["category"] == "car_seat"
56
+
57
+ def test_hamax_is_bicycle_trailer(self, hamax_config):
58
+ """Hamax is categorized as bicycle trailer."""
59
+ assert hamax_config["product"]["category"] == "bicycle_trailer"
60
+
61
+ def test_products_have_images(self, all_configs):
62
+ """All products have image URLs."""
63
+ for name, config in all_configs.items():
64
+ assert "image_url" in config["product"], f"{name}: Missing image_url"
65
+ assert config["product"]["image_url"].startswith("http"), \
66
+ f"{name}: image_url should be a URL"
67
+
68
+ def test_products_have_features(self, all_configs):
69
+ """All products have feature lists."""
70
+ for name, config in all_configs.items():
71
+ assert "features" in config["product"], f"{name}: Missing features"
72
+ assert len(config["product"]["features"]) > 0, f"{name}: Empty features list"
tests/test_calculations.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for core business calculations."""
2
+
3
+ import pytest
4
+
5
+
6
+ def calculate_eolrr(return_rate: float, grade_a: float, grade_b: float) -> float:
7
+ """Calculate End-of-Life Recovery Rate."""
8
+ return return_rate * (grade_a + grade_b)
9
+
10
+
11
+ def calculate_circular_profit(
12
+ new_unit_cost: float,
13
+ refurb_unit_cost: float,
14
+ revenue_per_cycle: float,
15
+ num_cycles: int
16
+ ) -> float:
17
+ """Calculate profit for circular model (1 product, N cycles)."""
18
+ total_cost = new_unit_cost + (num_cycles - 1) * refurb_unit_cost
19
+ total_revenue = num_cycles * revenue_per_cycle
20
+ return total_revenue - total_cost
21
+
22
+
23
+ def calculate_linear_profit(
24
+ new_unit_cost: float,
25
+ revenue_per_cycle: float,
26
+ num_cycles: int
27
+ ) -> float:
28
+ """Calculate profit for linear model (N products, 1 cycle each)."""
29
+ total_cost = num_cycles * new_unit_cost
30
+ total_revenue = num_cycles * revenue_per_cycle
31
+ return total_revenue - total_cost
32
+
33
+
34
+ class TestEoLRRCalculation:
35
+ """Test EoLRR calculation."""
36
+
37
+ def test_eolrr_with_perfect_returns(self):
38
+ """100% return rate, 100% grade A+B = 100% EoLRR."""
39
+ result = calculate_eolrr(1.0, 0.95, 0.05)
40
+ assert result == 1.0
41
+
42
+ def test_eolrr_with_partial_returns(self):
43
+ """90% return rate, 95% reusable = 85.5% EoLRR."""
44
+ result = calculate_eolrr(0.90, 0.80, 0.15)
45
+ assert abs(result - 0.855) < 0.001
46
+
47
+ def test_eolrr_zero_returns(self):
48
+ """0% return rate = 0% EoLRR."""
49
+ result = calculate_eolrr(0.0, 0.80, 0.15)
50
+ assert result == 0.0
51
+
52
+ def test_eolrr_from_config(self, besafe_config):
53
+ """Calculate EoLRR from actual config."""
54
+ assumptions = besafe_config["return_assumptions"]
55
+ dist = assumptions["grade_distribution"]
56
+ result = calculate_eolrr(
57
+ assumptions["return_rate"],
58
+ dist["a"],
59
+ dist["b"]
60
+ )
61
+ # BeSafe: 0.90 × (0.80 + 0.15) = 0.855
62
+ assert 0 < result < 1
63
+
64
+
65
+ class TestCircularVsLinearProfit:
66
+ """Test circular model beats linear model."""
67
+
68
+ def test_circular_beats_linear_after_one_cycle(self):
69
+ """Circular profit > linear profit for cycles > 1."""
70
+ new_cost = 100
71
+ refurb_cost = 30
72
+ revenue = 80
73
+
74
+ # At 2 cycles
75
+ circular = calculate_circular_profit(new_cost, refurb_cost, revenue, 2)
76
+ linear = calculate_linear_profit(new_cost, revenue, 2)
77
+ assert circular > linear, f"Circular ({circular}) should beat linear ({linear}) at 2 cycles"
78
+
79
+ # At 3 cycles
80
+ circular = calculate_circular_profit(new_cost, refurb_cost, revenue, 3)
81
+ linear = calculate_linear_profit(new_cost, revenue, 3)
82
+ assert circular > linear, f"Circular ({circular}) should beat linear ({linear}) at 3 cycles"
83
+
84
+ def test_advantage_increases_with_cycles(self):
85
+ """Circular advantage grows with more cycles."""
86
+ new_cost = 100
87
+ refurb_cost = 30
88
+ revenue = 80
89
+
90
+ advantages = []
91
+ for cycles in [2, 3, 4, 5]:
92
+ circular = calculate_circular_profit(new_cost, refurb_cost, revenue, cycles)
93
+ linear = calculate_linear_profit(new_cost, revenue, cycles)
94
+ advantages.append(circular - linear)
95
+
96
+ # Each advantage should be greater than the previous
97
+ for i in range(1, len(advantages)):
98
+ assert advantages[i] > advantages[i-1], \
99
+ f"Advantage should increase: {advantages[i-1]} -> {advantages[i]}"
100
+
101
+ def test_with_config_values(self, besafe_config):
102
+ """Test with actual config values."""
103
+ costs = besafe_config["costs"]
104
+ pricing = besafe_config["pricing"]
105
+ design = besafe_config["design"]
106
+
107
+ new_cost = costs["manufacturing_unit_cost"] + costs["logistics"]["delivery"] + costs["logistics"]["return"]
108
+ refurb_cost = costs["refurbishment"]["grade_a"] + costs["logistics"]["delivery"] + costs["logistics"]["return"]
109
+ revenue = pricing["lease_monthly"] * pricing["lease_term_months"]
110
+ cycles = design["max_cycles"]
111
+
112
+ circular = calculate_circular_profit(new_cost, refurb_cost, revenue, cycles)
113
+ linear = calculate_linear_profit(new_cost, revenue, cycles)
114
+
115
+ assert circular > linear, f"Circular ({circular}) should beat linear ({linear})"
116
+
117
+
118
+ class TestCostPerUse:
119
+ """Test cost per use calculations."""
120
+
121
+ def test_cost_per_use_decreases_with_cycles(self):
122
+ """Amortized cost per use decreases as cycles increase."""
123
+ new_cost = 100
124
+ refurb_cost = 30
125
+
126
+ costs_per_use = []
127
+ for cycles in range(1, 6):
128
+ total_cost = new_cost + (cycles - 1) * refurb_cost
129
+ cost_per_use = total_cost / cycles
130
+ costs_per_use.append(cost_per_use)
131
+
132
+ # Each cost per use should be less than or equal to previous
133
+ for i in range(1, len(costs_per_use)):
134
+ assert costs_per_use[i] <= costs_per_use[i-1], \
135
+ f"Cost per use should decrease: {costs_per_use[i-1]} -> {costs_per_use[i]}"
136
+
137
+
138
+ class TestFleetScaleEconomics:
139
+ """Test fleet scale calculations."""
140
+
141
+ def test_customers_served_equals_fleet_times_cycles(self):
142
+ """Total customers = fleet size × cycles."""
143
+ fleet = 1000
144
+ cycles = 3
145
+ customers = fleet * cycles
146
+ assert customers == 3000
147
+
148
+ def test_products_saved_calculation(self):
149
+ """Products saved = linear products - circular products."""
150
+ fleet = 5000
151
+ cycles = 3
152
+ customers = fleet * cycles # 15000
153
+
154
+ linear_products = customers # Need 15000 products
155
+ circular_products = fleet # Need only 5000 products
156
+ saved = linear_products - circular_products
157
+
158
+ assert saved == 10000
159
+
160
+ def test_circular_fleet_profit_beats_linear(self):
161
+ """Fleet-level circular profit beats linear for same customer count."""
162
+ fleet = 1000
163
+ cycles = 3
164
+ new_cost = 100
165
+ refurb_cost = 30
166
+ revenue = 80
167
+
168
+ customers = fleet * cycles # 3000
169
+
170
+ # Circular: manufacture fleet once, refurb for subsequent cycles
171
+ circular_cost = fleet * new_cost + fleet * (cycles - 1) * refurb_cost
172
+ circular_revenue = customers * revenue
173
+ circular_profit = circular_revenue - circular_cost
174
+
175
+ # Linear: manufacture new product for each customer
176
+ linear_cost = customers * new_cost
177
+ linear_revenue = customers * revenue
178
+ linear_profit = linear_revenue - linear_cost
179
+
180
+ assert circular_profit > linear_profit
tests/test_config.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for product configuration validation."""
2
+
3
+ import pytest
4
+
5
+
6
+ # Required top-level sections
7
+ REQUIRED_SECTIONS = ["product", "design", "costs", "pricing", "return_assumptions", "environmental"]
8
+
9
+ # Required product fields
10
+ REQUIRED_PRODUCT_FIELDS = ["name", "category", "retail_price"]
11
+
12
+ # Required design fields
13
+ REQUIRED_DESIGN_FIELDS = ["lifetime_years", "use_cycle_years", "max_cycles"]
14
+
15
+ # Required cost fields
16
+ REQUIRED_COST_FIELDS = ["manufacturing_unit_cost"]
17
+
18
+
19
+ class TestConfigStructure:
20
+ """Test that configs have required structure."""
21
+
22
+ def test_besafe_has_required_sections(self, besafe_config):
23
+ """BeSafe config has all required sections."""
24
+ for section in REQUIRED_SECTIONS:
25
+ assert section in besafe_config, f"Missing section: {section}"
26
+
27
+ def test_hamax_has_required_sections(self, hamax_config):
28
+ """Hamax config has all required sections."""
29
+ for section in REQUIRED_SECTIONS:
30
+ assert section in hamax_config, f"Missing section: {section}"
31
+
32
+ def test_all_configs_have_required_sections(self, all_configs):
33
+ """All product configs have required sections."""
34
+ for name, config in all_configs.items():
35
+ for section in REQUIRED_SECTIONS:
36
+ assert section in config, f"{name}: Missing section: {section}"
37
+
38
+
39
+ class TestProductSection:
40
+ """Test product section validation."""
41
+
42
+ def test_product_has_required_fields(self, all_configs):
43
+ """Product section has required fields."""
44
+ for name, config in all_configs.items():
45
+ for field in REQUIRED_PRODUCT_FIELDS:
46
+ assert field in config["product"], f"{name}: Missing product.{field}"
47
+
48
+ def test_retail_price_positive(self, all_configs):
49
+ """Retail price is positive."""
50
+ for name, config in all_configs.items():
51
+ price = config["product"]["retail_price"]
52
+ assert price > 0, f"{name}: retail_price must be positive, got {price}"
53
+
54
+
55
+ class TestDesignSection:
56
+ """Test design section validation."""
57
+
58
+ def test_design_has_required_fields(self, all_configs):
59
+ """Design section has required fields."""
60
+ for name, config in all_configs.items():
61
+ for field in REQUIRED_DESIGN_FIELDS:
62
+ assert field in config["design"], f"{name}: Missing design.{field}"
63
+
64
+ def test_lifetime_greater_than_use_cycle(self, all_configs):
65
+ """Design lifetime >= use cycle years."""
66
+ for name, config in all_configs.items():
67
+ lifetime = config["design"]["lifetime_years"]
68
+ use_cycle = config["design"]["use_cycle_years"]
69
+ assert lifetime >= use_cycle, f"{name}: lifetime_years ({lifetime}) < use_cycle_years ({use_cycle})"
70
+
71
+ def test_max_cycles_positive(self, all_configs):
72
+ """Max cycles is positive."""
73
+ for name, config in all_configs.items():
74
+ cycles = config["design"]["max_cycles"]
75
+ assert cycles > 0, f"{name}: max_cycles must be positive, got {cycles}"
76
+
77
+
78
+ class TestCostsSection:
79
+ """Test costs section validation."""
80
+
81
+ def test_manufacturing_cost_positive(self, all_configs):
82
+ """Manufacturing cost is positive."""
83
+ for name, config in all_configs.items():
84
+ cost = config["costs"]["manufacturing_unit_cost"]
85
+ assert cost > 0, f"{name}: manufacturing_unit_cost must be positive, got {cost}"
86
+
87
+ def test_refurbishment_costs_exist(self, all_configs):
88
+ """Refurbishment costs exist for grades A, B, C."""
89
+ for name, config in all_configs.items():
90
+ refurb = config["costs"].get("refurbishment", {})
91
+ assert "grade_a" in refurb, f"{name}: Missing refurbishment.grade_a"
92
+ assert "grade_b" in refurb, f"{name}: Missing refurbishment.grade_b"
93
+
94
+ def test_refurb_costs_ascending(self, all_configs):
95
+ """Refurbishment costs: grade_a <= grade_b."""
96
+ for name, config in all_configs.items():
97
+ refurb = config["costs"]["refurbishment"]
98
+ assert refurb["grade_a"] <= refurb["grade_b"], \
99
+ f"{name}: grade_a cost ({refurb['grade_a']}) > grade_b ({refurb['grade_b']})"
100
+
101
+
102
+ class TestReturnAssumptions:
103
+ """Test return assumptions validation."""
104
+
105
+ def test_return_rate_valid_range(self, all_configs):
106
+ """Return rate is between 0 and 1."""
107
+ for name, config in all_configs.items():
108
+ rate = config["return_assumptions"]["return_rate"]
109
+ assert 0 <= rate <= 1, f"{name}: return_rate must be 0-1, got {rate}"
110
+
111
+ def test_grade_distribution_sums_to_one(self, all_configs):
112
+ """Grade distribution (a + b + c) sums to 1."""
113
+ for name, config in all_configs.items():
114
+ dist = config["return_assumptions"]["grade_distribution"]
115
+ total = dist.get("a", 0) + dist.get("b", 0) + dist.get("c", 0)
116
+ assert abs(total - 1.0) < 0.01, f"{name}: grade distribution sums to {total}, not 1.0"
117
+
118
+
119
+ class TestMaterialsBOM:
120
+ """Test materials BOM validation (if present)."""
121
+
122
+ def test_bom_weights_positive(self, all_configs):
123
+ """BOM component weights are positive."""
124
+ for name, config in all_configs.items():
125
+ if "materials" in config and "bom" in config["materials"]:
126
+ for comp_name, comp in config["materials"]["bom"].items():
127
+ weight = comp.get("weight_kg", 0)
128
+ assert weight > 0, f"{name}: {comp_name} weight must be positive"
129
+
130
+ def test_recyclable_materials_have_recovery_value(self, all_configs):
131
+ """Recyclable materials should have recovery value."""
132
+ for name, config in all_configs.items():
133
+ if "materials" in config and "bom" in config["materials"]:
134
+ for comp_name, comp in config["materials"]["bom"].items():
135
+ if comp.get("recyclable", False) and "virgin_cost_per_kg" in comp:
136
+ assert "recovery_value_per_kg" in comp, \
137
+ f"{name}: {comp_name} is recyclable but missing recovery_value_per_kg"