test_analyze_TFT_refactored_verbose.py ダウンロード/コピー
test_analyze_TFT_refactored_verbose.py をダウンロード
test_analyze_TFT_refactored_verbose.py
test_analyze_TFT_refactored_verbose.py
1#!/usr/bin/env python3
2"""Tests for analyze_TFT_refactored.py using artificial TFT data.
3
4This file can be used in two ways.
5
61. Normal pytest execution with the default seed and noise level::
7
8 pytest -q -s test_analyze_TFT_refactored.py
9
102. Standalone execution with configurable seed and noise level::
11
12 python test_analyze_TFT_refactored.py --seed 12345 --noise-level 0.005
13
14The standalone mode internally calls pytest after setting environment variables.
15It also prints a human-readable description of each test case by default.
16The target script is assumed to be placed next to this test file, but it can be
17changed by --target-script or the TFT_TARGET_SCRIPT environment variable.
18
19Artificial-data cases
20---------------------
21Case A: Ideal noiseless data
22 Saturation-region data follow Id = Ioff + A_sat * max(Vg - Vth, 0)^2.
23 Linear-region data follow Id = Ioff + A_lin * max(Vg - Vth, 0).
24 These data are used for strict numerical checks of Vth and mobility.
25
26Case B: Noisy but reproducible data
27 The same model is used, but multiplicative Gaussian noise is added with a
28 fixed random seed. These tests check reproducibility and that the analysis
29 does not break. Because the maximum-slope method is intentionally sensitive
30 to noise, these tests do not require close agreement with the true values.
31
32Case C: Edge/error data
33 Missing columns, too-short data, low-current data that never reach the SS
34 target current, and zero/negative current points are checked.
35"""
36
37from __future__ import annotations
38
39import argparse
40import importlib.util
41import os
42import sys
43from pathlib import Path
44from typing import NamedTuple
45
46# Use a non-interactive backend before importing the target script.
47os.environ.setdefault("MPLBACKEND", "Agg")
48
49import numpy as np
50import pandas as pd
51import pytest
52
53
54DEFAULT_SEED = 12345
55DEFAULT_NOISE_LEVEL = 0.005
56
57# Known parameters for artificial data.
58TRUE_VTH = 2.0
59TRUE_SS = 0.4 # V/dec, used only in subthreshold artificial data.
60TRUE_IOFF = 1.0e-15
61TRUE_MU_SAT = 10.0e-4 # 10 cm^2/Vs expressed as m^2/Vs.
62TRUE_MU_FE = 8.0e-4 # 8 cm^2/Vs expressed as m^2/Vs.
63VDS_SAT = 10.0
64VDS_LIN = 0.1
65VG_MIN = -5.0
66VG_MAX = 15.0
67N_POINTS = 201
68
69
70class ArtificialData(NamedTuple):
71 """Container for saturation and linear-region artificial Id-Vg data."""
72
73 sat: pd.DataFrame
74 lin: pd.DataFrame
75
76
77def runtime_seed() -> int:
78 """Return the seed used by tests."""
79
80 return int(os.environ.get("TFT_TEST_SEED", DEFAULT_SEED))
81
82
83def runtime_noise_level() -> float:
84 """Return the relative noise level used by Case B tests."""
85
86 return float(os.environ.get("TFT_TEST_NOISE_LEVEL", DEFAULT_NOISE_LEVEL))
87
88
89def load_target_module():
90 """Dynamically import the target analysis script from a file path."""
91
92 default_target = Path(__file__).with_name("analyze_TFT_refactored.py")
93 target_from_argv = None
94 if __name__ == "__main__":
95 # In standalone mode, the target script has to be known before argparse
96 # runs because this module imports the target script at import time.
97 for i, arg in enumerate(sys.argv):
98 if arg == "--target-script" and i + 1 < len(sys.argv):
99 target_from_argv = sys.argv[i + 1]
100 break
101 if arg.startswith("--target-script="):
102 target_from_argv = arg.split("=", 1)[1]
103 break
104
105 target_path = Path(
106 os.environ.get("TFT_TARGET_SCRIPT", target_from_argv or str(default_target))
107 ).resolve()
108 if not target_path.exists():
109 raise FileNotFoundError(
110 f"Target script was not found: {target_path}\n"
111 "Set TFT_TARGET_SCRIPT or run this test next to analyze_TFT_refactored.py."
112 )
113
114 spec = importlib.util.spec_from_file_location("analyze_TFT_refactored_under_test", target_path)
115 if spec is None or spec.loader is None:
116 raise ImportError(f"Could not create import specification for {target_path}")
117
118 module = importlib.util.module_from_spec(spec)
119 # dataclass needs sys.modules[__module__] to exist during dynamic import.
120 sys.modules[spec.name] = module
121 spec.loader.exec_module(module)
122 return module
123
124
125tft = None if __name__ == "__main__" else load_target_module()
126
127
128TEST_DETAILS: dict[str, dict[str, object]] = {
129 "test_case_a_ideal_data_recovers_vth_and_mobility": {
130 "case": "Case A",
131 "title": "理想データでしきい値電圧と移動度を再現できるか",
132 "purpose": "ノイズなしの人工TFTデータを使い、解析式に対応する既知パラメータを正しく回収できるか確認します。",
133 "data": [
134 f"Vth={TRUE_VTH:g} V, muSAT={TRUE_MU_SAT * 1.0e4:g} cm^2/Vs, "
135 f"muFE={TRUE_MU_FE * 1.0e4:g} cm^2/Vs",
136 f"Vg={VG_MIN:g}..{VG_MAX:g} V, 点数={N_POINTS}",
137 ],
138 "checks": [
139 "SAT/LINのVthが真値に近い",
140 "muSAT/muFEが真値に近い",
141 "Ionが正の値になる",
142 ],
143 },
144 "test_case_b_noisy_data_are_reproducible": {
145 "case": "Case B",
146 "title": "ノイズ付きデータがseed固定で再現できるか",
147 "purpose": "乱数seedを固定したとき、同じノイズ付き人工データが完全に再生成できることを確認します。",
148 "data": [
149 "multiplicative Gaussian noise",
150 "seedは --seed または TFT_TEST_SEED で指定",
151 "noise_levelは --noise-level または TFT_TEST_NOISE_LEVEL で指定",
152 ],
153 "checks": [
154 "SATデータのId配列が一致",
155 "LINデータのId配列が一致",
156 ],
157 },
158 "test_case_b_noisy_data_do_not_break_analysis": {
159 "case": "Case B",
160 "title": "ノイズ付きデータでも解析が破綻しないか",
161 "purpose": "最大傾き法がノイズに敏感であることを前提に、厳密一致ではなく有限値・正値・範囲内かを確認します。",
162 "data": [
163 "Case Bと同じノイズ付き人工データ",
164 "seed/noise_levelは実行時に変更可能",
165 ],
166 "checks": [
167 "SAT/LINのVthが有限値",
168 "VthがVg範囲内",
169 "mobilityとIonが正の値",
170 ],
171 },
172 "test_cli_creates_expected_output_files": {
173 "case": "CLI/output",
174 "title": "コマンドライン処理で期待ファイルが生成されるか",
175 "purpose": "人工データをExcelに保存し、main()経由で解析して、CSV・PNG・ログが作られるか確認します。",
176 "data": [
177 "pytestのtmp_pathに一時Excel入力を作成",
178 "出力先も一時ディレクトリを使用",
179 ],
180 "checks": [
181 "main()の終了コードが0",
182 "解析CSV・summary CSV・log CSV・PNGが存在",
183 "出力ファイルが空でない",
184 "summaryに必要列がある",
185 ],
186 },
187 "test_case_c_missing_required_columns_raise_value_error": {
188 "case": "Case C",
189 "title": "必須列がない入力で明確にValueErrorになるか",
190 "purpose": "Id列などが欠けた不正入力に対し、曖昧に失敗せず、分かりやすい例外を出すか確認します。",
191 "data": [
192 "Vg, Vdのみを持ちId列がないDataFrame",
193 ],
194 "checks": [
195 "SAT解析でValueError",
196 "LIN解析でValueError",
197 "メッセージに missing required columns を含む",
198 ],
199 },
200 "test_case_c_short_data_raise_value_error_for_vth": {
201 "case": "Case C",
202 "title": "点数不足データでVth計算が明確に失敗するか",
203 "purpose": "rolling slopeを計算できない短いデータに対し、原因が分かる例外を返すか確認します。",
204 "data": [
205 "3点のみのDataFrame",
206 "rolling_window=7",
207 ],
208 "checks": [
209 "SAT解析でValueError",
210 "LIN解析でValueError",
211 "メッセージに No valid slope values を含む",
212 ],
213 },
214 "test_case_c_low_current_sets_ss_and_von_to_nan": {
215 "case": "Case C",
216 "title": "ターゲット電流未達でSS/VonがNaNになるか",
217 "purpose": "低電流のままでtarget_currentに到達しない場合、無理にSS/Vonを計算しないことを確認します。",
218 "data": [
219 "全点が target_current の 1e-3 倍",
220 ],
221 "checks": [
222 "SATのSS/VonがNaN",
223 "LINのSS/VonがNaN",
224 ],
225 },
226 "test_case_c_zero_and_negative_currents_are_ignored_for_log_and_sqrt": {
227 "case": "Case C",
228 "title": "ゼロ・負電流がlog/sqrt処理で除外されるか",
229 "purpose": "Id<=0の点をlogId/rootId計算に使わず、NaNとして扱えるか確認します。",
230 "data": [
231 "人工SATデータの一部を 0, -1e-12, -1 に置換",
232 ],
233 "checks": [
234 "該当点のId_rm/logId/rootIdがNaN",
235 "残りのデータでmobilityが正に求まる",
236 ],
237 },
238 "test_case_c_missing_input_file_returns_nonzero_exit_code": {
239 "case": "Case C",
240 "title": "入力ファイル欠損時に非ゼロ終了コードを返すか",
241 "purpose": "CLI実行時にExcel入力が存在しない場合、正常終了と誤認しない終了コードになるか確認します。",
242 "data": [
243 "存在しないlin/sat Excelパス",
244 ],
245 "checks": [
246 "main()の終了コードが0以外",
247 ],
248 },
249}
250
251
252def show_test_details_enabled() -> bool:
253 """Return whether human-readable test descriptions should be printed.
254
255 This function intentionally uses only an environment variable so that the
256 test file works as a normal single-file pytest test. Pytest hook functions
257 and custom options are not reliable when they are defined only inside a test
258 module; they are normally placed in conftest.py or a plugin.
259 """
260
261 return os.environ.get("TFT_TEST_SHOW_DETAILS", "1") not in {
262 "0", "false", "False", "no", "NO"
263 }
264
265
266def _print_line(message: str = "") -> None:
267 """Print one line immediately.
268
269 With ``pytest -s`` or ``--capture=no``, these lines are shown in the
270 console. Without ``-s``, pytest captures them and usually shows them only
271 when a test fails.
272 """
273
274 print(message, flush=True)
275
276
277def _print_test_detail(test_name: str) -> None:
278 """Print the purpose, data, and checks for one test function."""
279
280 if not show_test_details_enabled():
281 return
282
283 detail = TEST_DETAILS.get(test_name)
284 if detail is None:
285 return
286
287 title = f"{detail['case']} | {detail['title']}"
288 _print_line()
289 _print_line("-" * 78)
290 _print_line(title)
291 _print_line("-" * 78)
292 _print_line(f"目的: {detail['purpose']}")
293
294 data_lines = detail.get("data", [])
295 if data_lines:
296 _print_line("データ条件:")
297 for line in data_lines:
298 _print_line(f" - {line}")
299
300 check_lines = detail.get("checks", [])
301 if check_lines:
302 _print_line("確認項目:")
303 for line in check_lines:
304 _print_line(f" - {line}")
305
306
307@pytest.fixture(scope="session", autouse=True)
308def _print_test_plan_once():
309 """Print the whole test-plan header once per pytest session.
310
311 This autouse fixture is discovered even when this file is run directly by
312 pytest, unlike pytest hook functions placed in an ordinary test module.
313 """
314
315 if show_test_details_enabled():
316 target_path = Path(
317 os.environ.get(
318 "TFT_TARGET_SCRIPT",
319 Path(__file__).with_name("analyze_TFT_refactored.py"),
320 )
321 ).resolve()
322 _print_line()
323 _print_line("=" * 78)
324 _print_line("TFT解析テスト: 実行内容")
325 _print_line("=" * 78)
326 _print_line(f"対象スクリプト: {target_path}")
327 _print_line(f"seed: {runtime_seed()}")
328 _print_line(f"noise_level: {runtime_noise_level()}")
329 _print_line("テスト分類: Case A=理想データ, Case B=ノイズ/再現性, Case C=異常系・エッジケース")
330 yield
331
332
333@pytest.fixture(autouse=True)
334def _print_each_test_detail(request: pytest.FixtureRequest):
335 """Print test details before each test and a compact result after it."""
336
337 test_name = request.node.name.split("[")[0]
338 _print_test_detail(test_name)
339 try:
340 yield
341 except BaseException:
342 if show_test_details_enabled():
343 _print_line(f"結果: [FAIL] {test_name}")
344 raise
345 else:
346 if show_test_details_enabled():
347 _print_line(f"結果: [PASS] {test_name}")
348
349
350def make_vg_grid() -> np.ndarray:
351 """Create the common Vg grid used by artificial transfer curves."""
352
353 return np.linspace(VG_MIN, VG_MAX, N_POINTS)
354
355
356def apply_relative_noise(values: np.ndarray, noise_level: float, rng: np.random.Generator) -> np.ndarray:
357 """Apply multiplicative Gaussian noise and keep current values positive.
358
359 Args:
360 values: Clean current values.
361 noise_level: Standard deviation of relative Gaussian noise. For example,
362 0.005 means approximately 0.5% relative noise.
363 rng: NumPy random-number generator.
364
365 Returns:
366 Positive noisy current values.
367 """
368
369 if noise_level <= 0:
370 return values.copy()
371
372 factor = 1.0 + rng.normal(loc=0.0, scale=noise_level, size=len(values))
373 # Keep the artificial current positive. This avoids testing negative-current
374 # handling in Case B; that is handled separately in Case C.
375 factor = np.clip(factor, 0.01, None)
376 return np.clip(values * factor, 1.0e-20, None)
377
378
379def make_sat_current(vg: np.ndarray, config, noise_level: float = 0.0, seed: int = DEFAULT_SEED) -> np.ndarray:
380 """Generate artificial saturation-region Id-Vg current.
381
382 For Vg < Vth, a simple subthreshold exponential is used. For Vg >= Vth,
383 the ideal square-law saturation model is used.
384 """
385
386 a_sat = config.channel_width * config.cox * TRUE_MU_SAT / (2.0 * config.channel_length)
387 id_sub = TRUE_IOFF * 10.0 ** ((vg - TRUE_VTH) / TRUE_SS)
388 id_on = TRUE_IOFF + a_sat * np.maximum(vg - TRUE_VTH, 0.0) ** 2
389 clean = np.where(vg < TRUE_VTH, id_sub, id_on)
390 return apply_relative_noise(clean, noise_level, np.random.default_rng(seed))
391
392
393def make_lin_current(vg: np.ndarray, config, noise_level: float = 0.0, seed: int = DEFAULT_SEED) -> np.ndarray:
394 """Generate artificial linear-region Id-Vg current.
395
396 For Vg < Vth, a simple subthreshold exponential is used. For Vg >= Vth,
397 the low-Vd linear-region model is used.
398 """
399
400 a_lin = config.channel_width / config.channel_length * config.cox * TRUE_MU_FE * VDS_LIN
401 id_sub = TRUE_IOFF * 10.0 ** ((vg - TRUE_VTH) / TRUE_SS)
402 id_on = TRUE_IOFF + a_lin * np.maximum(vg - TRUE_VTH, 0.0)
403 clean = np.where(vg < TRUE_VTH, id_sub, id_on)
404 return apply_relative_noise(clean, noise_level, np.random.default_rng(seed + 1))
405
406
407def make_artificial_data(config, noise_level: float = 0.0, seed: int = DEFAULT_SEED) -> ArtificialData:
408 """Create paired saturation and linear-region artificial Id-Vg DataFrames."""
409
410 vg = make_vg_grid()
411 sat = pd.DataFrame(
412 {
413 "Vg": vg,
414 "Vd": np.full_like(vg, VDS_SAT),
415 "Id": make_sat_current(vg, config, noise_level=noise_level, seed=seed),
416 }
417 )
418 lin = pd.DataFrame(
419 {
420 "Vg": vg,
421 "Vd": np.full_like(vg, VDS_LIN),
422 "Id": make_lin_current(vg, config, noise_level=noise_level, seed=seed),
423 }
424 )
425 return ArtificialData(sat=sat, lin=lin)
426
427
428def make_low_current_data(config) -> ArtificialData:
429 """Create data that never reach the target current used for SS/Von."""
430
431 vg = make_vg_grid()
432 low_id = np.full_like(vg, config.target_current * 1.0e-3, dtype=float)
433 sat = pd.DataFrame({"Vg": vg, "Vd": np.full_like(vg, VDS_SAT), "Id": low_id})
434 lin = pd.DataFrame({"Vg": vg, "Vd": np.full_like(vg, VDS_LIN), "Id": low_id})
435 return ArtificialData(sat=sat, lin=lin)
436
437
438def write_excel_inputs(data: ArtificialData, directory: Path) -> tuple[Path, Path]:
439 """Write artificial input Excel files and return (lin_path, sat_path)."""
440
441 lin_path = directory / "IdVg-Vd0.1.xlsx"
442 sat_path = directory / "IdVg-Vd10.xlsx"
443 data.lin.to_excel(lin_path, index=False)
444 data.sat.to_excel(sat_path, index=False)
445 return lin_path, sat_path
446
447
448# -----------------------------------------------------------------------------
449# Case A: ideal data
450# -----------------------------------------------------------------------------
451def test_case_a_ideal_data_recovers_vth_and_mobility() -> None:
452 """Ideal data should recover the known Vth and mobility values."""
453
454 config = tft.AnalysisConfig()
455 data = make_artificial_data(config, noise_level=0.0, seed=runtime_seed())
456
457 sat_result = tft.analyze_idvg_sat(data.sat, config)
458 lin_result = tft.analyze_idvg_lin(data.lin, config)
459
460 assert sat_result.vth == pytest.approx(TRUE_VTH, abs=0.05)
461 assert lin_result.vth == pytest.approx(TRUE_VTH, abs=0.05)
462 assert sat_result.mobility == pytest.approx(TRUE_MU_SAT, rel=0.02)
463 assert lin_result.mobility == pytest.approx(TRUE_MU_FE, rel=0.02)
464 assert sat_result.ion > 0
465 assert lin_result.ion > 0
466
467
468# -----------------------------------------------------------------------------
469# Case B: noisy reproducible data
470# -----------------------------------------------------------------------------
471def test_case_b_noisy_data_are_reproducible() -> None:
472 """Noisy artificial data should be exactly reproducible for a fixed seed."""
473
474 config = tft.AnalysisConfig()
475 seed = runtime_seed()
476 noise_level = runtime_noise_level()
477
478 data1 = make_artificial_data(config, noise_level=noise_level, seed=seed)
479 data2 = make_artificial_data(config, noise_level=noise_level, seed=seed)
480
481 np.testing.assert_allclose(data1.sat["Id"].to_numpy(), data2.sat["Id"].to_numpy())
482 np.testing.assert_allclose(data1.lin["Id"].to_numpy(), data2.lin["Id"].to_numpy())
483
484
485def test_case_b_noisy_data_do_not_break_analysis() -> None:
486 """Noisy data should still produce finite positive summary values.
487
488 The original maximum-slope method can be very sensitive to noise, so this
489 test intentionally checks robustness rather than strict agreement with the
490 true parameters.
491 """
492
493 config = tft.AnalysisConfig()
494 data = make_artificial_data(config, noise_level=runtime_noise_level(), seed=runtime_seed())
495
496 sat_result = tft.analyze_idvg_sat(data.sat, config)
497 lin_result = tft.analyze_idvg_lin(data.lin, config)
498
499 assert np.isfinite(sat_result.vth)
500 assert np.isfinite(lin_result.vth)
501 assert VG_MIN <= sat_result.vth <= VG_MAX
502 assert VG_MIN <= lin_result.vth <= VG_MAX
503 assert sat_result.mobility > 0
504 assert lin_result.mobility > 0
505 assert sat_result.ion > 0
506 assert lin_result.ion > 0
507
508
509# -----------------------------------------------------------------------------
510# CLI/output test
511# -----------------------------------------------------------------------------
512def test_cli_creates_expected_output_files(tmp_path: Path) -> None:
513 """The command-line workflow should read Excel files and create outputs."""
514
515 config = tft.AnalysisConfig()
516 data = make_artificial_data(config, noise_level=0.0, seed=runtime_seed())
517 lin_path, sat_path = write_excel_inputs(data, tmp_path)
518 outdir = tmp_path / "result"
519
520 exit_code = tft.main(
521 [
522 "--lin", str(lin_path),
523 "--sat", str(sat_path),
524 "--outdir", str(outdir),
525 ]
526 )
527
528 assert exit_code == 0
529 expected_files = [
530 "IdVg-Vd10_analyze.csv",
531 "IdVg-Vd0.1_analyze.csv",
532 "output.csv",
533 "output_log.csv",
534 "rootIdVg.png",
535 "IdVg_LIN.png",
536 ]
537 for filename in expected_files:
538 path = outdir / filename
539 assert path.exists(), f"Missing output file: {path}"
540 assert path.stat().st_size > 0, f"Empty output file: {path}"
541
542 summary = pd.read_csv(outdir / "output.csv")
543 for column in ["Vth_SAT", "muSAT", "SS_SAT", "Ion_SAT", "Vth_LIN", "muFE", "SS_LIN", "Ion_LIN"]:
544 assert column in summary.columns
545
546
547# -----------------------------------------------------------------------------
548# Case C: edge/error data
549# -----------------------------------------------------------------------------
550def test_case_c_missing_required_columns_raise_value_error() -> None:
551 """Missing required columns should raise clear ValueError exceptions."""
552
553 config = tft.AnalysisConfig()
554 missing_id = pd.DataFrame({"Vg": [0.0, 1.0, 2.0], "Vd": [0.1, 0.1, 0.1]})
555
556 with pytest.raises(ValueError, match="missing required columns"):
557 tft.analyze_idvg_sat(missing_id, config)
558
559 with pytest.raises(ValueError, match="missing required columns"):
560 tft.analyze_idvg_lin(missing_id, config)
561
562
563def test_case_c_short_data_raise_value_error_for_vth() -> None:
564 """Too-short data should fail clearly because rolling slopes are unavailable."""
565
566 config = tft.AnalysisConfig(rolling_window=7)
567 short = pd.DataFrame(
568 {
569 "Vg": [0.0, 1.0, 2.0],
570 "Vd": [VDS_LIN, VDS_LIN, VDS_LIN],
571 "Id": [1.0e-15, 1.0e-12, 1.0e-10],
572 }
573 )
574
575 with pytest.raises(ValueError, match="No valid slope values"):
576 tft.analyze_idvg_sat(short, config)
577
578 with pytest.raises(ValueError, match="No valid slope values"):
579 tft.analyze_idvg_lin(short, config)
580
581
582def test_case_c_low_current_sets_ss_and_von_to_nan() -> None:
583 """If target current is never reached, SS and Von should be NaN."""
584
585 config = tft.AnalysisConfig()
586 data = make_low_current_data(config)
587
588 sat_result = tft.analyze_idvg_sat(data.sat, config)
589 lin_result = tft.analyze_idvg_lin(data.lin, config)
590
591 assert np.isnan(sat_result.ss)
592 assert np.isnan(sat_result.von)
593 assert np.isnan(lin_result.ss)
594 assert np.isnan(lin_result.von)
595
596
597def test_case_c_zero_and_negative_currents_are_ignored_for_log_and_sqrt() -> None:
598 """Zero/negative Id values should become NaN in Id_rm, logId, and rootId."""
599
600 config = tft.AnalysisConfig()
601 data = make_artificial_data(config, noise_level=0.0, seed=runtime_seed())
602 sat_df = data.sat.copy()
603
604 bad_indices = [5, 20, 40]
605 sat_df.loc[bad_indices[0], "Id"] = 0.0
606 sat_df.loc[bad_indices[1], "Id"] = -1.0e-12
607 sat_df.loc[bad_indices[2], "Id"] = -1.0
608
609 result = tft.analyze_idvg_sat(sat_df, config)
610
611 assert result.dataframe.loc[bad_indices, "Id_rm"].isna().all()
612 assert result.dataframe.loc[bad_indices, "logId"].isna().all()
613 assert result.dataframe.loc[bad_indices, "rootId"].isna().all()
614 assert result.mobility > 0
615
616
617def test_case_c_missing_input_file_returns_nonzero_exit_code(tmp_path: Path) -> None:
618 """main() should return a nonzero code when input files do not exist."""
619
620 outdir = tmp_path / "result"
621 exit_code = tft.main(
622 [
623 "--lin", str(tmp_path / "missing_lin.xlsx"),
624 "--sat", str(tmp_path / "missing_sat.xlsx"),
625 "--outdir", str(outdir),
626 ]
627 )
628
629 assert exit_code != 0
630
631
632# -----------------------------------------------------------------------------
633# Standalone wrapper
634# -----------------------------------------------------------------------------
635def parse_wrapper_args(argv: list[str] | None = None) -> argparse.Namespace:
636 """Parse arguments for standalone execution of this test file."""
637
638 parser = argparse.ArgumentParser(
639 description="Run pytest-based tests for analyze_TFT_refactored.py."
640 )
641 parser.add_argument(
642 "--seed",
643 type=int,
644 default=DEFAULT_SEED,
645 help=f"Random seed for noisy artificial data. Default: {DEFAULT_SEED}",
646 )
647 parser.add_argument(
648 "--noise-level",
649 type=float,
650 default=DEFAULT_NOISE_LEVEL,
651 help=f"Relative noise level for Case B artificial data. Default: {DEFAULT_NOISE_LEVEL}",
652 )
653 parser.add_argument(
654 "--target-script",
655 default=os.environ.get("TFT_TARGET_SCRIPT", str(Path(__file__).with_name("analyze_TFT_refactored.py"))),
656 help="Path to analyze_TFT_refactored.py. Default: next to this test file.",
657 )
658 parser.add_argument(
659 "--show-details",
660 type=int,
661 default=1,
662 choices=[0, 1],
663 help="Print detailed descriptions of test purpose/data/checks. 1=yes, 0=no. Default: 1",
664 )
665 parser.add_argument(
666 "--pytest-args",
667 default="-q -s",
668 help="Extra arguments passed to pytest as a single string. Default: -q -s",
669 )
670 return parser.parse_args(argv)
671
672
673def main(argv: list[str] | None = None) -> int:
674 """Run pytest with seed/noise options supplied through environment variables."""
675
676 args = parse_wrapper_args(argv)
677 os.environ["TFT_TEST_SEED"] = str(args.seed)
678 os.environ["TFT_TEST_NOISE_LEVEL"] = str(args.noise_level)
679 os.environ["TFT_TARGET_SCRIPT"] = str(Path(args.target_script).resolve())
680 os.environ["TFT_TEST_SHOW_DETAILS"] = str(args.show_details)
681
682 pytest_args = args.pytest_args.split() + [str(Path(__file__).resolve())]
683 return int(pytest.main(pytest_args))
684
685
686if __name__ == "__main__":
687 raise SystemExit(main())