|
1 | 1 | import pytest |
| 2 | +import tempfile |
| 3 | +import os |
2 | 4 | import calphy.helpers as ch |
3 | 5 | import numpy as np |
4 | 6 |
|
@@ -35,6 +37,50 @@ def test_validate_spring_constants(): |
35 | 37 | e = ch.validate_spring_constants(d) |
36 | 38 | assert e[0] == 1 |
37 | 39 |
|
38 | | - d = [1, np.NaN, 4] |
| 40 | + d = [1, np.nan, 4] |
39 | 41 | e = ch.validate_spring_constants(d) |
40 | 42 | assert e[1] == 1 |
| 43 | + |
| 44 | +def test_prepare_log_no_handler_accumulation(): |
| 45 | + """ |
| 46 | + Calling prepare_log twice for the same file should not accumulate handlers. |
| 47 | + Each call should reset to exactly one file handler. |
| 48 | + """ |
| 49 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 50 | + logfile = os.path.join(tmpdir, "test.log") |
| 51 | + |
| 52 | + logger1 = ch.prepare_log(logfile) |
| 53 | + assert len(logger1.handlers) == 1, "Should have exactly 1 handler after first call" |
| 54 | + |
| 55 | + logger2 = ch.prepare_log(logfile) |
| 56 | + assert len(logger2.handlers) == 1, "Should still have exactly 1 handler after second call" |
| 57 | + assert logger1 is logger2, "Should return the same logger object" |
| 58 | + |
| 59 | +def test_prepare_log_no_cross_contamination(): |
| 60 | + """ |
| 61 | + Two independent calculations logging to different files must not |
| 62 | + write into each other's log files. |
| 63 | + """ |
| 64 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 65 | + log1 = os.path.join(tmpdir, "calc1.log") |
| 66 | + log2 = os.path.join(tmpdir, "calc2.log") |
| 67 | + |
| 68 | + logger1 = ch.prepare_log(log1) |
| 69 | + logger1.info("message from calc1") |
| 70 | + |
| 71 | + logger2 = ch.prepare_log(log2) |
| 72 | + logger2.info("message from calc2") |
| 73 | + |
| 74 | + # Flush all handlers |
| 75 | + for h in logger1.handlers: |
| 76 | + h.flush() |
| 77 | + for h in logger2.handlers: |
| 78 | + h.flush() |
| 79 | + |
| 80 | + content1 = open(log1).read() |
| 81 | + content2 = open(log2).read() |
| 82 | + |
| 83 | + assert "message from calc1" in content1, "calc1.log should contain calc1 message" |
| 84 | + assert "message from calc2" not in content1, "calc1.log must NOT contain calc2 message" |
| 85 | + assert "message from calc2" in content2, "calc2.log should contain calc2 message" |
| 86 | + assert "message from calc1" not in content2, "calc2.log must NOT contain calc1 message" |
0 commit comments