-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_cli.py
More file actions
599 lines (482 loc) · 16.5 KB
/
Copy pathtest_cli.py
File metadata and controls
599 lines (482 loc) · 16.5 KB
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
"""Tests for the BREOS command line interface."""
import csv
import json
from pathlib import Path
import pytest
from breos import cli
EXAMPLE_CONFIGS = sorted((Path(__file__).resolve().parents[1] / "configs" / "examples").glob("*.toml"))
class FakeApp:
seen_config = None
simulated = False
def __init__(self, config):
self.config = config
FakeApp.seen_config = config
def simulate(self):
FakeApp.simulated = True
def result(self):
return {
"grid_independence_pct": 42.0,
"config": self.config,
}
def test_run_from_flags_outputs_json(monkeypatch, capsys):
monkeypatch.setattr(cli, "App", FakeApp)
exit_code = cli.main(
[
"run",
"--location",
"porto",
"--n-modules",
"10",
"--annual-consumption-kwh",
"4000",
"--battery-kwh",
"5.0",
"--cost-preset",
"residential-pt",
"--emissions-country",
"pt",
"--load-profile",
"6",
"--rlp-directory",
"/tmp/external-rlp",
]
)
assert exit_code == 0
assert FakeApp.simulated is True
assert FakeApp.seen_config["location"] == "porto"
assert FakeApp.seen_config["n_modules"] == 10
assert FakeApp.seen_config["annual_consumption_kwh"] == 4000
assert FakeApp.seen_config["battery_kwh"] == 5.0
assert FakeApp.seen_config["cost_preset"] == "residential_pt"
assert FakeApp.seen_config["emissions_country"] == "PT"
assert FakeApp.seen_config["load_profile"] == "6"
assert FakeApp.seen_config["rlp_directory"] == "/tmp/external-rlp"
output = json.loads(capsys.readouterr().out)
assert output["grid_independence_pct"] == 42.0
def test_run_flag_sell_price_inflation_reaches_config(monkeypatch, capsys):
monkeypatch.setattr(cli, "App", FakeApp)
exit_code = cli.main(
[
"run",
"--location",
"porto",
"--n-modules",
"10",
"--annual-consumption-kwh",
"4000",
"--sell-price-inflation",
"0.03",
]
)
assert exit_code == 0
assert FakeApp.seen_config["sell_price_inflation"] == 0.03
def test_run_bifacial_flags_reach_config(monkeypatch, capsys):
monkeypatch.setattr(cli, "App", FakeApp)
exit_code = cli.main(
[
"run",
"--location",
"porto",
"--n-modules",
"10",
"--annual-consumption-kwh",
"4000",
"--pv-module",
"Generic_600W_Bifacial",
"--bifacial-model",
"infinite_sheds",
"--gcr",
"0.35",
"--pvrow-height",
"1.5",
"--pvrow-pitch",
"6.0",
]
)
assert exit_code == 0
assert FakeApp.seen_config["bifacial_model"] == "infinite_sheds"
assert FakeApp.seen_config["gcr"] == 0.35
assert FakeApp.seen_config["pvrow_height"] == 1.5
assert FakeApp.seen_config["pvrow_pitch"] == 6.0
def test_run_from_toml_config_with_cli_override(monkeypatch, tmp_path):
monkeypatch.setattr(cli, "App", FakeApp)
config_path = tmp_path / "experiment.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 8
annual_consumption_kwh = 3500
battery_kwh = 0
cost_preset = "residential_pt"
""".strip(),
encoding="utf-8",
)
output_path = tmp_path / "result.json"
exit_code = cli.main(
[
"run",
"--config",
str(config_path),
"--battery-kwh",
"5.0",
"--output",
str(output_path),
]
)
assert exit_code == 0
assert FakeApp.seen_config["n_modules"] == 8
assert FakeApp.seen_config["battery_kwh"] == 5.0
assert json.loads(output_path.read_text(encoding="utf-8"))["grid_independence_pct"] == 42.0
def test_invalid_json_config_reports_filename(tmp_path, capsys):
config_path = tmp_path / "broken_config.json"
config_path.write_text('{"location": "porto",', encoding="utf-8")
exit_code = cli.main(["run", "--config", str(config_path)])
assert exit_code == 1
stderr = capsys.readouterr().err
assert "Invalid JSON in" in stderr
assert "broken_config.json" in stderr
def test_list_locations_outputs_packaged_keys(capsys):
exit_code = cli.main(["list", "locations"])
assert exit_code == 0
output = capsys.readouterr().out
assert "porto: Porto, Portugal" in output
assert "Europe/Lisbon" in output
def test_list_modules_json_outputs_catalog(capsys):
exit_code = cli.main(["list", "modules", "--json"])
assert exit_code == 0
output = json.loads(capsys.readouterr().out)
assert any(row["key"] == "Generic_400W" and row["power_w"] == 400 for row in output)
bifacial = next(row for row in output if row["key"] == "Generic_600W_Bifacial")
assert bifacial["bifaciality"] == 0.7
def test_list_modules_text_identifies_bifaciality(capsys):
exit_code = cli.main(["list", "modules"])
assert exit_code == 0
output = capsys.readouterr().out
assert "Generic_600W_Bifacial: 600 W" in output
assert "bifaciality 70.0%" in output
def test_temperature_model_flags_expose_sapm_and_reject_unsourced_noct_metadata(capsys):
sapm_exit = cli.main(
[
"run",
"--location",
"porto",
"--n-modules",
"10",
"--annual-consumption-kwh",
"4000",
"--temperature-model",
"sapm-close-mount-glass-glass",
"--dry-run",
]
)
assert sapm_exit == 0
noct_exit = cli.main(
[
"run",
"--location",
"porto",
"--n-modules",
"10",
"--annual-consumption-kwh",
"4000",
"--temperature-model",
"noct-sam",
"--dry-run",
]
)
assert noct_exit == 1
assert "NOCT metadata" in capsys.readouterr().err
def test_list_battery_models_exposes_scientific_metadata(capsys):
exit_code = cli.main(["list", "battery-models", "--json"])
assert exit_code == 0
output = json.loads(capsys.readouterr().out)
assert len(output) == 14
lfp = next(row for row in output if row["key"] == "lfp_gr_250ah_prismatic")
assert lfp["chemistry"] == "LFP/graphite"
assert lfp["cell_format"] == "prismatic"
assert lfp["experimental_range"]["cycling_temperature_c"] == [10, 45]
assert lfp["release_phase"] == "core"
def test_run_cli_threads_blast_selection(monkeypatch, tmp_path):
monkeypatch.setattr(cli, "App", FakeApp)
FakeApp.seen_config = None
config_path = tmp_path / "quickstart.toml"
config_path.write_text(
'location = "porto"\nn_modules = 10\nannual_consumption_kwh = 4000\nbattery_kwh = 5.0\n',
encoding="utf-8",
)
exit_code = cli.main(
[
"run",
"--config",
str(config_path),
"--degradation-engine",
"blast",
"--blast-model",
"lfp_gr_250ah_prismatic",
]
)
assert exit_code == 0
assert FakeApp.seen_config["degradation_engine"] == "blast"
assert FakeApp.seen_config["blast_model"] == "lfp_gr_250ah_prismatic"
def test_validate_config_summarizes_without_simulation(tmp_path, capsys):
config_path = tmp_path / "quickstart.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 10
annual_consumption_kwh = 4000
battery_kwh = 5.0
cost_preset = "residential_pt"
emissions_country = "PT"
""".strip(),
encoding="utf-8",
)
exit_code = cli.main(["validate-config", str(config_path)])
assert exit_code == 0
output = capsys.readouterr().out
assert "Config OK" in output
assert "Location: porto (Europe/Lisbon)" in output
assert "PV: 10 modules" in output
assert "Inverter AC rating" in output
def test_recommended_pv_example_validates(capsys):
config_path = Path(__file__).resolve().parents[1] / "configs" / "examples" / "recommended-pv.toml"
exit_code = cli.main(["validate-config", str(config_path)])
assert exit_code == 0
output = capsys.readouterr().out
assert "Config OK" in output
assert "PV: 8 modules, 4.400 kWp" in output
def test_example_configs_are_discovered():
# A moved or renamed directory would otherwise turn the parametrised test
# below into zero silent cases.
assert len(EXAMPLE_CONFIGS) >= 10
@pytest.mark.parametrize("config_path", EXAMPLE_CONFIGS, ids=lambda path: path.name)
def test_shipped_example_configs_validate(config_path, capsys):
exit_code = cli.main(["validate-config", str(config_path)])
assert exit_code == 0
assert "Config OK" in capsys.readouterr().out
def test_validate_config_rejects_malformed_sweep(tmp_path, capsys):
config_path = tmp_path / "invalid-sweep.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 10
annual_consumption_kwh = 4000
[sweep]
battery_kwh = []
""".strip()
)
exit_code = cli.main(["validate-config", str(config_path)])
assert exit_code == 1
assert "sweep.battery_kwh must be a non-empty array" in capsys.readouterr().err
def test_run_dry_run_outputs_resolved_config_without_simulating(monkeypatch, tmp_path):
monkeypatch.setattr(cli, "App", FakeApp)
FakeApp.simulated = False
config_path = tmp_path / "quickstart.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 10
annual_consumption_kwh = 4000
battery_kwh = 5.0
""".strip(),
encoding="utf-8",
)
output_path = tmp_path / "resolved.json"
exit_code = cli.main(["run", "--config", str(config_path), "--dry-run", "--output", str(output_path)])
assert exit_code == 0
assert FakeApp.simulated is False
output = json.loads(output_path.read_text(encoding="utf-8"))
assert output["valid"] is True
assert output["location"]["key"] == "porto"
assert output["pv"]["n_modules"] == 10
assert output["pv"]["losses"]["components_pct"]["shading"] == 3.0
assert 14.0 < output["pv"]["losses"]["combined_pct"] < 15.0
assert output["battery"]["degradation_engine"] == "native"
assert output["battery"]["blast_model"] is None
def test_run_iam_model_override_is_reflected_in_dry_run(tmp_path):
output_path = tmp_path / "resolved.json"
exit_code = cli.main(
[
"run",
"--location",
"porto",
"--n-modules",
"8",
"--annual-consumption-kwh",
"3000",
"--iam-model",
"physical",
"--dry-run",
"--output",
str(output_path),
]
)
assert exit_code == 0
assert json.loads(output_path.read_text(encoding="utf-8"))["pv"]["iam_model"] == "physical"
def test_run_dry_run_reports_bifacial_geometry(monkeypatch, tmp_path):
monkeypatch.setattr(cli, "App", FakeApp)
output_path = tmp_path / "resolved.json"
exit_code = cli.main(
[
"run",
"--location",
"porto",
"--n-modules",
"10",
"--annual-consumption-kwh",
"4000",
"--pv-module",
"Generic_600W_Bifacial",
"--bifacial-model",
"infinite_sheds",
"--pvrow-height",
"1.5",
"--pvrow-pitch",
"6.0",
"--dry-run",
"--output",
str(output_path),
]
)
assert exit_code == 0
pv = json.loads(output_path.read_text(encoding="utf-8"))["pv"]
assert pv["bifacial_model"] == "infinite_sheds"
assert pv["gcr"] == 0.35
assert pv["pvrow_height"] == 1.5
assert pv["pvrow_pitch"] == 6.0
def test_sweep_expands_grid_and_writes_combined_csv(monkeypatch, tmp_path, capsys):
seen_configs = []
class SweepFakeApp:
def __init__(self, config):
self.config = config
seen_configs.append(config)
def simulate(self):
return None
def result(self):
return {
"grid_independence_pct": 40.0 + self.config["n_modules"],
"npv_savings_eur": 1000.0 + self.config["battery_kwh"],
"yearly": [{"year": 1}],
}
monkeypatch.setattr(cli, "App", SweepFakeApp)
config_path = tmp_path / "sweep.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 8
annual_consumption_kwh = 3500
battery_kwh = 0
cost_preset = "residential_pt"
[sweep]
n_modules = [8, 10]
battery_kwh = [0.0, 5.0]
""".strip(),
encoding="utf-8",
)
output_path = tmp_path / "sweep.csv"
exit_code = cli.main(["sweep", "--config", str(config_path), "--output", str(output_path), "--json"])
assert exit_code == 0
assert len(seen_configs) == 4
payload = json.loads(capsys.readouterr().out)
assert payload["runs"] == 4
rows = list(csv.DictReader(output_path.open(encoding="utf-8")))
assert len(rows) == 4
assert rows[0]["param_n_modules"] == "8"
assert rows[-1]["param_battery_kwh"] == "5.0"
assert "yearly" not in rows[0]
assert rows[0]["grid_independence_pct"] == "48.0"
def test_sweep_applies_dotted_cost_keys_without_mutating_base_config(monkeypatch, tmp_path, capsys):
seen_configs = []
class SweepFakeApp:
def __init__(self, config):
self.config = config
seen_configs.append(config)
def simulate(self):
return None
def result(self):
return {"npv_savings_eur": self.config["costs"]["electricity_cost"] * 1000}
monkeypatch.setattr(cli, "App", SweepFakeApp)
config_path = tmp_path / "cost-sweep.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 8
annual_consumption_kwh = 3500
cost_preset = "residential_pt"
[costs]
storage_cost_per_kwh = 420.0
[sweep]
"costs.electricity_cost" = [0.20, 0.30]
""".strip(),
encoding="utf-8",
)
output_path = tmp_path / "cost-sweep.csv"
exit_code = cli.main(["sweep", "--config", str(config_path), "--output", str(output_path), "--json"])
assert exit_code == 0
assert [config["costs"] for config in seen_configs] == [
{"storage_cost_per_kwh": 420.0, "electricity_cost": 0.20},
{"storage_cost_per_kwh": 420.0, "electricity_cost": 0.30},
]
rows = list(csv.DictReader(output_path.open(encoding="utf-8")))
assert [row["param_costs.electricity_cost"] for row in rows] == ["0.2", "0.3"]
assert [row["npv_savings_eur"] for row in rows] == ["200.0", "300.0"]
def test_sweep_accepts_unquoted_toml_dotted_cost_key(monkeypatch, tmp_path, capsys):
seen_configs = []
class SweepFakeApp:
def __init__(self, config):
seen_configs.append(config)
def simulate(self):
return None
def result(self):
return {}
monkeypatch.setattr(cli, "App", SweepFakeApp)
config_path = tmp_path / "nested-cost-sweep.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 8
annual_consumption_kwh = 3500
[sweep]
costs.electricity_cost = [0.20, 0.30]
""".strip(),
encoding="utf-8",
)
exit_code = cli.main(["sweep", "--config", str(config_path), "--output", str(tmp_path / "out.csv")])
assert exit_code == 0
assert [config["costs"]["electricity_cost"] for config in seen_configs] == [0.20, 0.30]
assert "Sweep: 2 runs" in capsys.readouterr().out
def test_validate_config_rejects_unknown_dotted_sweep_cost_key(tmp_path, capsys):
config_path = tmp_path / "invalid-cost-sweep.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 8
annual_consumption_kwh = 3500
[sweep]
"costs.electricty_cost" = [0.20, 0.30]
""".strip(),
encoding="utf-8",
)
exit_code = cli.main(["validate-config", str(config_path)])
assert exit_code == 1
error = capsys.readouterr().err
assert "Unknown sweep key 'costs.electricty_cost'" in error
assert "costs.electricity_cost" in error
def test_validate_config_rejects_dotted_sweep_key_outside_costs(tmp_path, capsys):
config_path = tmp_path / "invalid-nested-sweep.toml"
config_path.write_text(
"""
location = "porto"
n_modules = 8
annual_consumption_kwh = 3500
[sweep]
"location.foo" = ["ignored-before-validation"]
""".strip(),
encoding="utf-8",
)
exit_code = cli.main(["validate-config", str(config_path)])
assert exit_code == 1
error = capsys.readouterr().err
assert "Unknown sweep key 'location.foo'" in error
assert "Dotted keys are supported only under 'costs'" in error
assert "costs.electricity_cost" in error