Repository navigation
Expand file tree
/
Copy pathtest_config.py
More file actions
1406 lines (1045 loc) · 38.6 KB
/
Copy pathtest_config.py
File metadata and controls
1406 lines (1045 loc) · 38.6 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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for the config layer: the programmatic Config primitive and
the TOML file loader.
A Config bundles observe entries, a sink, instrumentation entries, and
the capture and sampling settings; apply() installs the lot and unwinds
itself on failure. The TOML loader is a thin schema over the same
primitive, with loud failures for anything it does not understand.
"""
import importlib
import os
import subprocess
import sys
import textwrap
import warnings
from pathlib import Path
from typing import Any
import pytest
import wrapt
from wrapture import (
AppliedConfig,
Config,
ConfigError,
ConfigWarning,
Event,
JSONLines,
ObserveEntry,
Sample,
Sink,
binding,
find_config,
load_config,
stack_frames,
)
class Collector(Sink):
def __init__(self) -> None:
self.entered: list[Event] = []
def on_enter(self, event: Event) -> None:
self.entered.append(event)
class OrderService:
limit = 10
def place(self) -> str:
return "placed"
def cancel(self) -> str:
return "cancelled"
def _audit(self) -> str:
return "audited"
@staticmethod
def validate(order: Any) -> Any:
return order
@classmethod
def build(cls) -> "OrderService":
return cls()
@property
def total(self) -> int:
return 1
class Receipt:
pass
def parse_widget(text: str) -> str:
return f"widget:{text}"
def label_widget(text: str, label: str) -> str:
return f"{label}:{text}"
def _unwind(applied: AppliedConfig) -> None:
applied.revert()
# ---------------------------------------------------------------------------
# the programmatic primitive
# ---------------------------------------------------------------------------
def test_apply_installs_bindings_and_registers_the_sink() -> None:
collector = Collector()
config = Config(
observe=[ObserveEntry(target=f"{__name__}:OrderService", name="place")],
sink=collector,
)
applied = config.apply()
try:
OrderService().place()
finally:
_unwind(applied)
assert [event.path for event in collector.entered] == [
f"{__name__}:OrderService.place"
]
# Unwinding took the binding off again: nothing further records.
OrderService().place()
assert len(collector.entered) == 1
def test_a_named_member_must_exist() -> None:
config = Config(
observe=[ObserveEntry(target=f"{__name__}:OrderService", name="dispatch")]
)
with pytest.raises(ConfigError, match="no member named 'dispatch'"):
config.apply()
def test_name_binds_a_property() -> None:
collector = Collector()
config = Config(
observe=[ObserveEntry(target=f"{__name__}:OrderService", name="total")],
sink=collector,
)
applied = config.apply()
try:
_ = OrderService().total
finally:
_unwind(applied)
(event,) = collector.entered
assert event.kind == "get"
def test_an_unimported_target_stays_pending() -> None:
# Deferral cannot tell a misspelled module from one not imported
# yet, so applying succeeds and the entry waits; the pending view
# and the shutdown report are where this surfaces.
config = Config(
observe=[ObserveEntry(target="no_such_module_anywhere:Thing", name="run")]
)
applied = config.apply()
try:
assert applied.bindings == ()
(entry,) = applied.pending
assert entry.target == "no_such_module_anywhere:Thing"
assert "no_such_module_anywhere:Thing" in applied.report()
finally:
_unwind(applied)
def test_match_selects_the_targets_own_routines_only() -> None:
# The pattern sees one level of one named container: routines from
# the class's own dict, including static and class methods, but
# never the property, the nested class, or plain data; exclude
# subtracts from the match.
config = Config(
observe=[
ObserveEntry(target=f"{__name__}:OrderService", match="*", exclude="_*")
]
)
applied = config.apply()
try:
selected = {bound.name for bound in applied.bindings}
finally:
_unwind(applied)
assert selected == {
"OrderService.place",
"OrderService.cancel",
"OrderService.validate",
"OrderService.build",
}
def test_match_on_a_module_skips_imported_functions_and_classes(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
# A module pattern selects only the functions the module itself
# defines: functions imported from elsewhere and classes (whose
# instantiation must never be bulk-wrapped) are skipped.
(tmp_path / "cfgtest_widgets.py").write_text(
textwrap.dedent(
"""
from os.path import join
def parse(text):
return text
def render(text):
return text
class Widget:
pass
"""
)
)
monkeypatch.syspath_prepend(str(tmp_path))
config = Config(observe=[ObserveEntry(target="cfgtest_widgets", match="*")])
applied = config.apply()
try:
importlib.import_module("cfgtest_widgets")
selected = {bound.name for bound in applied.bindings}
finally:
_unwind(applied)
assert selected == {"parse", "render"}
def test_match_skips_already_wrapped_members() -> None:
with binding(OrderService, "place"):
config = Config(
observe=[ObserveEntry(target=f"{__name__}:OrderService", match="place")]
)
with pytest.warns(ConfigWarning):
applied = config.apply()
try:
assert applied.bindings == ()
finally:
_unwind(applied)
def test_a_match_selecting_nothing_warns() -> None:
config = Config(
observe=[ObserveEntry(target=f"{__name__}:OrderService", match="handle_*")]
)
with pytest.warns(ConfigWarning, match="selected no members"):
applied = config.apply()
_unwind(applied)
def test_the_capture_override_applies_to_every_binding() -> None:
# The config's capture level rides on each binding, where it beats
# what the sink declares: "none" skips argument capture entirely
# even though the collector would ask for references.
collector = Collector()
config = Config(
observe=[ObserveEntry(target=__name__, name="parse_widget")],
sink=collector,
capture="none",
)
applied = config.apply()
try:
parse_widget("gear")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.arguments is None
def test_a_failed_apply_leaves_nothing_behind() -> None:
# The second entry fails, so the first entry's binding and the
# sink must both be gone again when the error propagates.
original = vars(OrderService)["place"]
collector = Collector()
config = Config(
observe=[
ObserveEntry(target=f"{__name__}:OrderService", name="place"),
ObserveEntry(target=f"{__name__}:OrderService", name="dispatch"),
],
sink=collector,
)
with pytest.raises(ConfigError, match="no member named 'dispatch'"):
config.apply()
assert vars(OrderService)["place"] is original
OrderService().place()
assert collector.entered == []
# ---------------------------------------------------------------------------
# deferral
# ---------------------------------------------------------------------------
def test_bindings_arrive_when_the_target_module_is_imported(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
(tmp_path / "cfg15_lazy_mod.py").write_text("def run(task):\n return task\n")
monkeypatch.syspath_prepend(str(tmp_path))
collector = Collector()
config = Config(
observe=[ObserveEntry(target="cfg15_lazy_mod", name="run")],
sink=collector,
)
applied = config.apply()
try:
# Nothing imported, nothing bound: the entry waits.
assert applied.bindings == ()
(entry,) = applied.pending
assert entry.target == "cfg15_lazy_mod"
# The application's own import is the trigger.
module = importlib.import_module("cfg15_lazy_mod")
arrived: tuple[Any, ...] = applied.bindings
(bound,) = arrived
assert bound.name == "run"
assert applied.pending == ()
module.run("job")
assert [event.path for event in collector.entered] == ["cfg15_lazy_mod:run"]
finally:
_unwind(applied)
def test_fire_time_validation_warns_and_the_import_continues(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
# Validation that needs the module (here a name that must exist)
# cannot run until the module arrives; fired inside an application
# import, the failure must not fail that import, so the entry is
# dropped with a warning and the module comes through usable.
(tmp_path / "cfg15_bad_mod.py").write_text("value = 1\n")
monkeypatch.syspath_prepend(str(tmp_path))
config = Config(observe=[ObserveEntry(target="cfg15_bad_mod", name="missing")])
applied = config.apply()
try:
with pytest.warns(ConfigWarning, match="no member named 'missing'"):
module = importlib.import_module("cfg15_bad_mod")
assert module.value == 1
assert applied.bindings == ()
assert applied.pending == ()
finally:
_unwind(applied)
def test_revert_neutralises_hooks_that_have_not_fired(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
# A wrapt hook cannot be unregistered, so reverting marks the
# record instead: the module's later import applies nothing.
(tmp_path / "cfg15_reverted_mod.py").write_text("def run(task):\n return task\n")
monkeypatch.syspath_prepend(str(tmp_path))
collector = Collector()
config = Config(
observe=[ObserveEntry(target="cfg15_reverted_mod", name="run")],
sink=collector,
)
applied = config.apply()
applied.revert()
applied.revert()
module = importlib.import_module("cfg15_reverted_mod")
assert applied.bindings == ()
assert not isinstance(module.run, wrapt.BaseObjectProxy)
module.run("job")
assert collector.entered == []
LAZY_PROBE = """
import sys
import wrapture
class Collector(wrapture.Sink):
def __init__(self):
self.entered = []
def on_enter(self, event):
self.entered.append(event)
collector = Collector()
applied = wrapture.Config(
observe=[wrapture.ObserveEntry(target="lazy_target", name="ping")],
sink=collector,
).apply()
lazy import lazy_target
assert "lazy_target" not in sys.modules
assert applied.bindings == ()
assert lazy_target.ping("x") == "pong:x"
assert [bound.name for bound in applied.bindings] == ["ping"]
assert [event.path for event in collector.entered] == ["lazy_target:ping"]
print("lazy-import-deferral-ok")
"""
@pytest.mark.skipif(
sys.version_info < (3, 15), reason="lazy import syntax arrived in 3.15"
)
def test_deferral_fires_when_a_lazy_import_reifies(tmp_path: Path) -> None:
# The lazy import statement imports nothing, so the entry stays
# pending; first use reifies the module through the normal import
# machinery, so the hook fires and the binding lands before the
# touched attribute is fetched. The 3.15-only syntax lives in a
# subprocess script so this file parses everywhere.
(tmp_path / "lazy_target.py").write_text(
"def ping(text):\n return f'pong:{text}'\n"
)
(tmp_path / "probe.py").write_text(LAZY_PROBE)
completed = subprocess.run(
[sys.executable, "probe.py"],
cwd=tmp_path,
capture_output=True,
text=True,
timeout=60,
)
assert completed.returncode == 0, completed.stderr
assert "lazy-import-deferral-ok" in completed.stdout
def test_report_lists_the_sink_applied_and_pending() -> None:
collector = Collector()
config = Config(
observe=[
ObserveEntry(target=f"{__name__}:OrderService", name="place"),
ObserveEntry(target="cfg15_ghost_mod", name="run"),
],
sink=collector,
)
applied = config.apply()
try:
text = applied.report()
assert "Collector" in text
assert f" {__name__}:OrderService.place" in text
assert "pending:" in text
assert " cfg15_ghost_mod" in text
finally:
_unwind(applied)
def test_the_shutdown_report_names_never_imported_targets() -> None:
from wrapture.config import _report_never_fired
config = Config(observe=[ObserveEntry(target="cfg15_ghost2_mod", name="run")])
applied = config.apply()
try:
with pytest.warns(ConfigWarning, match="cfg15_ghost2_mod"):
_report_never_fired()
finally:
_unwind(applied)
# A reverted record has nothing outstanding to report.
with warnings.catch_warnings():
warnings.simplefilter("error")
_report_never_fired()
# ---------------------------------------------------------------------------
# operational hardening
# ---------------------------------------------------------------------------
def test_a_tape_is_rejected_as_a_config_sink() -> None:
# A Tape retains every event; a config sink lives for the life of
# the process, so the combination is refused however deeply a
# composition buries it.
from wrapture import Depth, Fanout, Printer, Tape
with pytest.raises(ConfigError, match="Tape retains every event"):
Config(sink=Tape())
with pytest.raises(ConfigError, match="Tape retains every event"):
Config(sink=Fanout(Printer(), Depth(2, Tape())))
def test_redact_replaces_named_parameters_on_the_entrys_bindings() -> None:
collector = Collector()
config = Config(
observe=[ObserveEntry(target=__name__, name="parse_widget", redact="text")],
sink=collector,
)
applied = config.apply()
try:
parse_widget("secret-token")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.arguments == {"text": "<redacted>"}
def test_an_entrys_capture_beats_the_top_level_capture() -> None:
# The top-level "none" would drop every value, but an entry that
# asks for references keeps its own arguments and result.
collector = Collector()
config = Config(
observe=[
ObserveEntry(target=__name__, name="parse_widget", capture="reference")
],
sink=collector,
capture="none",
)
applied = config.apply()
try:
parse_widget("gear")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.arguments == {"text": "gear"}
assert event.result == "widget:gear"
def test_capture_result_drops_the_result_and_keeps_the_arguments() -> None:
collector = Collector()
config = Config(
observe=[
ObserveEntry(target=__name__, name="parse_widget", capture_result="none")
],
sink=collector,
)
applied = config.apply()
try:
parse_widget("gear")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.arguments == {"text": "gear"}
assert event.result is wrapt.MISSING
def test_capture_args_overrides_one_axis_of_the_entrys_capture() -> None:
# capture sets both axes on the entry; capture_args then takes the
# arguments axis down to type names while the result keeps the
# entry's level.
collector = Collector()
config = Config(
observe=[
ObserveEntry(
target=__name__,
name="parse_widget",
capture="reference",
capture_args="types",
)
],
sink=collector,
)
applied = config.apply()
try:
parse_widget("gear")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.arguments == {"text": "<str>"}
assert event.result == "widget:gear"
def test_redact_composes_over_the_entrys_capture_args_level() -> None:
# The named parameter is masked whatever the level; a second
# parameter shows the surrounding level is the entry's own.
collector = Collector()
config = Config(
observe=[
ObserveEntry(
target=__name__,
name="label_widget",
redact="text",
capture_args="types",
)
],
sink=collector,
)
applied = config.apply()
try:
label_widget("secret-token", "gear")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.arguments == {"text": "<redacted>", "label": "<str>"}
def test_a_bad_entry_capture_level_fails_the_build() -> None:
with pytest.raises(ConfigError, match="capture_result: capture level must be"):
ObserveEntry(target=__name__, name="parse_widget", capture_result="nope")
def test_redact_result_replaces_the_result_with_the_marker() -> None:
collector = Collector()
config = Config(
observe=[
ObserveEntry(target=__name__, name="parse_widget", redact_result=True)
],
sink=collector,
)
applied = config.apply()
try:
parse_widget("gear")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.arguments == {"text": "gear"}
assert event.result == "<redacted>"
def test_redact_result_refuses_a_capture_result_level() -> None:
with pytest.raises(ConfigError, match="capture_result has nothing to apply to"):
ObserveEntry(
target=__name__,
name="parse_widget",
redact_result=True,
capture_result="summary",
)
def test_redact_marker_applies_to_the_list_and_the_result() -> None:
collector = Collector()
config = Config(
observe=[
ObserveEntry(
target=__name__,
name="parse_widget",
redact="text",
redact_result=True,
redact_marker="***",
)
],
sink=collector,
)
applied = config.apply()
try:
parse_widget("gear")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.arguments == {"text": "***"}
assert event.result == "***"
def test_redact_marker_needs_a_redaction_to_apply_to() -> None:
with pytest.raises(ConfigError, match="redact_marker needs a redact list"):
ObserveEntry(target=__name__, name="parse_widget", redact_marker="***")
def test_stack_records_the_calling_frame_on_the_entrys_bindings() -> None:
collector = Collector()
config = Config(
observe=[ObserveEntry(target=__name__, name="parse_widget", stack="caller")],
sink=collector,
)
applied = config.apply()
try:
parse_widget("gear")
finally:
_unwind(applied)
(event,) = collector.entered
assert event.stack is not None
(frame,) = stack_frames(event.stack)
assert (
frame.function == "test_stack_records_the_calling_frame_on_the_entrys_bindings"
)
@pytest.mark.parametrize("value", ["sideways", 0, -1, True])
def test_a_bad_stack_value_fails_the_build(value: Any) -> None:
with pytest.raises(ConfigError, match="stack must be"):
ObserveEntry(target=__name__, name="parse_widget", stack=value)
def test_the_loader_accepts_the_redaction_and_stack_keys(tmp_path: Path) -> None:
source = tmp_path / "trace.toml"
source.write_text(
textwrap.dedent(
f"""
[[observe]]
target = "{__name__}"
name = "parse_widget"
redact_result = true
redact_marker = "***"
stack = 3
"""
)
)
config = load_config(source)
entry = config.observe[0]
assert entry.redact_result is True
assert entry.redact_marker == "***"
assert entry.stack == 3
def test_the_loader_accepts_the_capture_keys(tmp_path: Path) -> None:
source = tmp_path / "trace.toml"
source.write_text(
textwrap.dedent(
f"""
[[observe]]
target = "{__name__}"
name = "parse_widget"
capture = "summary"
capture_args = "types"
capture_result = "none"
"""
)
)
config = load_config(source)
entry = config.observe[0]
assert entry.capture == "summary"
assert entry.capture_args == "types"
assert entry.capture_result == "none"
def test_the_loader_accepts_a_redact_key(tmp_path: Path) -> None:
source = tmp_path / "trace.toml"
source.write_text(
textwrap.dedent(
f"""
[[observe]]
target = "{__name__}"
name = "parse_widget"
redact = ["text"]
"""
)
)
config = load_config(source)
assert config.observe[0].redact == ("text",)
def test_inherit_false_strips_only_wrapture_from_the_trigger(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("AUTOWRAPT_BOOTSTRAP", "othertool,wrapture")
applied = Config(inherit=False).apply()
try:
assert os.environ["AUTOWRAPT_BOOTSTRAP"] == "othertool"
finally:
_unwind(applied)
# Alone on the list, the variable goes entirely.
monkeypatch.setenv("AUTOWRAPT_BOOTSTRAP", "wrapture")
applied = Config(inherit=False).apply()
try:
assert "AUTOWRAPT_BOOTSTRAP" not in os.environ
finally:
_unwind(applied)
def test_inherit_defaults_to_leaving_the_environment_alone(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("AUTOWRAPT_BOOTSTRAP", "wrapture")
applied = Config().apply()
try:
assert os.environ["AUTOWRAPT_BOOTSTRAP"] == "wrapture"
finally:
_unwind(applied)
def test_inherit_must_be_a_bool(tmp_path: Path) -> None:
with pytest.raises(ConfigError, match="inherit must be true or false"):
Config(inherit="no") # type: ignore[arg-type]
source = tmp_path / "trace.toml"
source.write_text('inherit = "no"\n')
with pytest.raises(ConfigError, match="inherit must be true or false"):
load_config(source)
def test_suspend_and_resume_toggle_the_whole_config() -> None:
collector = Collector()
config = Config(
observe=[ObserveEntry(target=f"{__name__}:OrderService", name="place")],
sink=collector,
)
applied = config.apply()
try:
applied.suspend()
OrderService().place()
assert collector.entered == []
(bound,) = applied.bindings
assert bound.suspended_calls == 1
applied.resume()
OrderService().place()
assert len(collector.entered) == 1
finally:
_unwind(applied)
def test_a_pending_entry_firing_while_suspended_applies_suspended(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
(tmp_path / "cfg16_late_mod.py").write_text("def run(task):\n return task\n")
monkeypatch.syspath_prepend(str(tmp_path))
collector = Collector()
config = Config(
observe=[ObserveEntry(target="cfg16_late_mod", name="run")],
sink=collector,
)
applied = config.apply()
try:
applied.suspend()
module = importlib.import_module("cfg16_late_mod")
module.run("job")
assert collector.entered == []
applied.resume()
module.run("job")
assert len(collector.entered) == 1
finally:
_unwind(applied)
# ---------------------------------------------------------------------------
# entry validation
# ---------------------------------------------------------------------------
def test_name_and_match_are_mutually_exclusive() -> None:
with pytest.raises(ConfigError, match="mutually exclusive"):
ObserveEntry(target="mod:Thing", name="run", match="r*")
def test_one_of_name_or_match_is_required() -> None:
with pytest.raises(ConfigError, match="one of name or match is required"):
ObserveEntry(target="mod:Thing")
def test_exclude_requires_match() -> None:
with pytest.raises(ConfigError, match="exclude only applies to match"):
ObserveEntry(target="mod:Thing", name="run", exclude="_*")
def test_a_target_has_at_most_one_colon() -> None:
with pytest.raises(ConfigError, match="single colon"):
ObserveEntry(target="mod:Thing:run", name="go")
# ---------------------------------------------------------------------------
# the TOML loader
# ---------------------------------------------------------------------------
def test_load_config_reads_the_full_schema(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
# pythonpath entries anchor to the config file's directory and are
# prepended before references resolve, so the sink factory can
# live in an uninstalled module right next to the config file.
ops = tmp_path / "ops"
ops.mkdir()
(ops / "cfgtest_sinks.py").write_text(
textwrap.dedent(
"""
from wrapture import Sink
class Probe(Sink):
def __init__(self, tag):
self.tag = tag
def make_sink(tag="default"):
return Probe(tag)
"""
)
)
source = tmp_path / "trace.toml"
source.write_text(
textwrap.dedent(
f"""
pythonpath = "ops"
capture = "summary"
[[observe]]
target = "{__name__}:OrderService"
match = "*"
exclude = "_*"
[[observe]]
target = "{__name__}"
name = ["parse_widget"]
[[sink]]
type = "cfgtest_sinks:make_sink"
tag = "from-config"
"""
)
)
monkeypatch.setattr(sys, "path", list(sys.path))
config = load_config(source)
assert sys.path[0] == str(ops)
first, second = config.observe
assert first.target == f"{__name__}:OrderService"
assert first.match == ("*",)
assert first.exclude == ("_*",)
assert second.name == ("parse_widget",)
assert type(config.sink).__name__ == "Probe"
assert getattr(config.sink, "tag", None) == "from-config"
assert config.capture == "summary"
def test_load_config_builds_builtin_sinks(tmp_path: Path) -> None:
# The path is embedded with forward slashes: in a TOML basic
# string a backslash starts an escape sequence, so the native
# Windows form would not even parse.
source = tmp_path / "trace.toml"
out = (tmp_path / "out.jsonl").as_posix()
source.write_text(f'[[sink]]\ntype = "jsonlines"\npath = "{out}"\n')
config = load_config(source)
assert isinstance(config.sink, JSONLines)
def test_load_config_passes_printer_options_through(tmp_path: Path) -> None:
from wrapture import Printer
source = tmp_path / "trace.toml"
source.write_text(
'[[sink]]\ntype = "printer"\n'
f'path = "{(tmp_path / "trace.log").as_posix()}"\n'
"timestamps = true\ntiming = false\n"
)
config = load_config(source)
# Compared as paths: the TOML spells the path with forward slashes,
# which Windows accepts but does not print back.
assert isinstance(config.sink, Printer)
assert config.sink._path is not None