-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtest_passgithelper.py
More file actions
1466 lines (1261 loc) · 49.6 KB
/
test_passgithelper.py
File metadata and controls
1466 lines (1261 loc) · 49.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
import configparser
import logging
from collections.abc import Generator, Sequence
from contextlib import nullcontext
from dataclasses import dataclass
from os import getenv, pathsep
from pathlib import Path
from shutil import which
from subprocess import CalledProcessError
from typing import ClassVar, Text, TypeAlias, cast
from unittest.mock import ANY
import pytest
from pytest_mock import MockerFixture, MockType
import passgithelper
CapsysType: TypeAlias = pytest.CaptureFixture[str]
CaplogType: TypeAlias = pytest.LogCaptureFixture
@dataclass
class HelperConfig:
"""Used by the ``helper_config`` fixture to configure test setup and teardown.
Check the attributes documentation below for more details.
The ``helper_config`` fixture also makes the ``HelperConfig`` data available to the
test implementation by yielding it as part of the ``HelperConfigAndMock`` object
after test setup is done. To access it, tests must explicitly add ``helper_config``
to their function signature. Used in this way, it allows tests to adapt their
behavior to the provided parametrization data. It also allows tests to dynamically
configure the teardown part of the ``helper_function`` fixture from their
implementatoin (see ``mock_co_expect_call`` below).
Attributes:
xdg_dir:
Used by ``helper_config`` to configure the directory containing the
pass-git-helper ini/mapping file (default: None).
request:
Used by ``helper_config`` to simulate the request data provided by git via
``stdin`` (default: "").
entry_data:
Used by ``helper_config`` to simulated the password store entry data
returned for ``entry_name`` by ``pass``. Also used to configure the
``subprocess.check_output`` mock which simulates calling ``pass``. If
``entry_data`` is provides, the setup done by ``helper_config`` mimics a
successful ``pass``word retrieval. With ``entry_data=None`` (the default) or
``entry_data=b""``, ``helper_config`` mimics a missing password store entry.
entry_name:
Name of the password store entry (aka `pass_target`) to retrieve. It mainly
gets used in the teardown part of ``helper_config`` to check that it is
contained in the the command line options provided to ``pass`` (default:
None). It can also be used to adapt test implementation behaviour to a given
parametrization.
patch_ensure_password_is_file:
When set to False (which is the default), ``helper_config`` will patch the
``patch_ensure_password_is_file(..)`` function. Only change this to ``True``
for tests of the ``patch_ensure_password_is_file(..)`` function.
mock_co_expect_call:
With the default (``True``), ``helper_config`` will add ``assert_called_*``
checks for the ``subprocess.check_output`` mock during teardown. When set to
``False``, these asserts will be skipped.
out_expected:
Document the expected output on ``stdout`` in the test parametrization. Will
automatically be checked when using the
``teardown_helper_capsys_checks(..)`` function.
err_expected:
Same as ``out_expected``, but for ``stderr`` instead of ``stdout``.
"""
xdg_dir: str | None = None
request: str = ""
entry_data: bytes | None = None
entry_name: str | None = None
patch_ensure_password_is_file: bool = True
mock_co_expect_call: bool = True
out_expected: str = ""
err_expected: str = ""
def get_host(self) -> str | None:
"""Get the host contained in ``request``."""
if not self.request:
return None
for line in self.request.splitlines():
param = line.split("=")
if len(param) > 1 and param[0] == "host":
return param[1]
return None
def get_pass_target(self, default: str | None = None) -> str | None:
"""Get the ``entry_name`` (aka `pass_target`) with optional default."""
return self.entry_name if self.entry_name is not None else default
@dataclass
class HelperConfigAndMock:
"""Generated value of the ``helper_config`` fixture.
Attributes:
test_params:
Test parametrization data.
mock_co:
Mock for ``subprocess.check_output`` as used in the
passgithelper.get_password(..) function.
"""
test_params: HelperConfig
mock_co: MockType
def setup_helper_load_first_config_and_request(
mocker: MockerFixture, test_params: HelperConfig
) -> None:
"""Use values from ``test_params`` to setup ``load_first_config()`` and ``readlines()`` mocks.
Intended to be called from a test fixture or directly from a test.
"""
_ = mocker.patch(
"xdg.BaseDirectory.load_first_config", return_value=test_params.xdg_dir
)
_ = mocker.patch(
"sys.stdin.readlines",
return_value=test_params.request.splitlines(keepends=True),
)
def setup_helper_parse_request_mock(
mocker: MockerFixture | None,
test_params: HelperConfig,
use_wildcard_section: bool = False,
**kwargs: str,
) -> configparser.ConfigParser | None:
"""Create simple mapping/config from ``test_params`` and use it to mock ``parse_mapping``.
The mapping gets created as follows:
1. The ``host`` request parameter gets used to create a section. If
``use_wildcard_section`` is True, a ``*`` gets appended to ``host`` before adding
the section.
2. As a next step, if ``test_params.get_pass_target()`` returns a non-empty string,
it gets added as ``target`` to the ``host`` section.
3. Any ``kwargs`` also get added to the ``host`` section.
The resulting ini/mapping object is then used as return value of the
``passgithelper.parse_mapping`` function using a mock object (this step is skipped
if ``mocker`` is ``None``).
Intended to be called from a test fixture or directly from a test.
Note: If you want a ``target`` in the ``host`` section of the created ConfigParser
object it should be added via ``test_params.entry_name``, not via ``kwargs``.
Otherwise automatic ``assert_called_*`` performed by the ``helper_config`` fixture
will fail or will need to be disabled.
Args:
mocker:
Used to patch the ``passgithelper.parse_mapping`` function. May be none to
skip the patching.
test_params:
Test parameters.
use_wildcard_section:
If True, the host section is created with a trailing ``*``.
kwargs:
Any ``kwargs`` are added to the ``host`` section of the created
ConfigParser object.
Returns:
The created ``ConfigParser`` object in case of success, ``None`` otherwise.
"""
# git host to use as section in created config
host = test_params.get_host()
if not host:
return None
else:
host = f"{host}*" if use_wildcard_section else host
# create ini (mapping)
ini = configparser.ConfigParser()
ini.add_section(host)
section = ini[host]
if pass_target := test_params.get_pass_target():
section.update(target=pass_target)
section.update(kwargs)
if mocker is not None:
# mock parse_request
_ = mocker.patch("passgithelper.parse_mapping", return_value=ini)
return ini
def teardown_helper_capsys_checks(
capsys: CapsysType,
test_params: HelperConfig,
out_use_equals: bool = False,
err_use_equals: bool = False,
) -> None:
"""Teardown helper which checks stdout/stderr dependening on ``test_params``.
Asserts that ``capsys.readouterr()`` matches
``test_params..{out,err}_expected``.
Intended to be called from a test fixture or directly from a test.
Args:
capsys:
pytest capsys fixture used to access stout/sterr.
test_params:
``HelperConfig`` object containing ``out_expected``/``err_expected``
out_use_equals:
By default, ``test_params.out_expected`` is checked using ``in``.
With ``out_use_equals=True`` the comparison is done using ``==``.
err_use_equals:
By default, ``test_params.err_expected`` is checked using ``in``.
With ``err_use_equals=True`` the comparison is done using ``==``.
"""
out, err = capsys.readouterr()
if test_params.out_expected:
if out_use_equals:
assert out == test_params.out_expected
else:
assert test_params.out_expected in out
else:
assert not out
if test_params.err_expected:
if err_use_equals:
assert err == test_params.err_expected
else:
assert test_params.err_expected in err
else:
assert not err
@pytest.fixture
def helper_config(
mocker: MockerFixture, request: pytest.FixtureRequest
) -> Generator[HelperConfigAndMock]:
test_params = cast("HelperConfig", request.param)
setup_helper_load_first_config_and_request(mocker, test_params)
if test_params.patch_ensure_password_is_file:
_ = mocker.patch("passgithelper.ensure_password_is_file")
subprocess_mock = mocker.patch("subprocess.check_output")
if test_params.entry_data:
subprocess_mock.return_value = test_params.entry_data
else:
subprocess_mock.side_effect = CalledProcessError(
returncode=1,
cmd=["pass", "show", test_params.get_pass_target() or "unknown"],
)
yield HelperConfigAndMock(test_params, subprocess_mock)
if test_params.mock_co_expect_call:
subprocess_mock.assert_called_once()
subprocess_mock.assert_called_with(
["pass", "show", test_params.entry_name], env=ANY
)
else:
subprocess_mock.assert_not_called()
@pytest.fixture
def setup_mock_gpg(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Manipulatest ``PATH`` in order to get ``pass`` to use the local mock gpg(2)."""
gpg_mock_dir = str(Path.cwd() / "test_data" / "dummy-password-store" / "bin")
monkeypatch.setenv("PATH", gpg_mock_dir, prepend=pathsep)
@pytest.fixture
def setup_teardown_wo_subprocess_mock(
capsys: CapsysType,
mocker: MockerFixture,
request: pytest.FixtureRequest,
) -> Generator[HelperConfig]:
"""Simplified setup/teardown fixture for ``passgithelper.main`` tests.
This is for tests which don't require the ``subprocess.check_output`` mock.
"""
test_params = cast("HelperConfig", request.param)
setup_helper_load_first_config_and_request(mocker, test_params)
password_store_dir = Path.cwd() / "test_data" / "dummy-password-store"
_ = setup_helper_parse_request_mock(
mocker,
test_params,
use_wildcard_section=True,
# make sure that `pass` uses the dummy password store
password_store_dir=str(password_store_dir),
username_extractor="regex_search",
)
yield test_params
teardown_helper_capsys_checks(capsys, test_params)
def test_handle_skip_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("PASS_GIT_HELPER_SKIP", raising=False)
passgithelper.handle_skip()
# should do nothing normally
def test_handle_skip_exits(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("PASS_GIT_HELPER_SKIP", "1")
with pytest.raises(SystemExit, match=r"^6$"):
passgithelper.handle_skip()
@pytest.mark.parametrize(
argnames=("argv", "env", "expected"),
argvalues=[
(["get"], {}, False),
(["--skip-fs-checks", "get"], {}, True),
(["get", "--skip-fs-checks"], {}, True),
(["get"], {"PASS_GIT_HELPER_SKIP_FS_CHECKS": "1"}, True),
(["get"], {"PASS_GIT_HELPER_SKIP_FS_CHECKS": "11"}, True),
(["get"], {"PASS_GIT_HELPER_SKIP_FS_CHECKS": "off"}, True),
(["get"], {"PASS_GIT_HELPER_SKIP_FS_CHECKS": "false"}, True),
(["get"], {"PASS_GIT_HELPER_SKIP_FS_CHECKS": ""}, False),
(["get"], {"PASS_GIT_HELPER_SKIP_FS_CHECKS": "0"}, False),
(["--skip-fs-checks", "get"], {"PASS_GIT_HELPER_SKIP_FS_CHECKS": "0"}, True),
],
)
def test_skip_fs_checks_in_function_parse_args(
monkeypatch: pytest.MonkeyPatch,
argv: list[str],
env: dict[str, str],
expected: bool,
) -> None:
"""Check handling of ``--skip-fs-checks`` in ``parse_arguments(..)``.
Runs ``passgithelper.parse_arguments`` with different combinations of the
``--skip-fs-checks`` CLI option and the ``PASS_GIT_HELPER_SKIP_FS_CHECKS``
environment variable and verifies the result by checking the value of the
``skip_fs_checks`` attribute of the namespace object returned by
``passgithelper.parse_arguments(..)``.
"""
for k, v in env.items():
monkeypatch.setenv(name=k, value=v)
opt = passgithelper.parse_arguments(argv=argv)
assert opt.skip_fs_checks == expected
def test_mapping_option_with_non_existing_file(capsys: CapsysType) -> None:
"""Test handling of ``--mapping`` option with a non-existing file name."""
nonexisting_ini_file = "___this_file_d0es_not_exist___.notIn1"
err_expected = f"No such file or directory: '{nonexisting_ini_file}'"
with pytest.raises(SystemExit, match=r"^2$"):
passgithelper.main(["--mapping", nonexisting_ini_file])
out, err = capsys.readouterr()
assert not out
assert err_expected in err
class TestPasswordStoreDirSelection:
"""Test password store directory selection.
The password store directory used by ``pass`` can either be set via the
``PASSWORD_STORE_DIR`` environment variable or via the
``password_store_dir`` option in the ini file. In case both are present, the
ini file option overrides the environment variable.
Empty values are ignored (as if they have not been set).
The different variants are tested here.
"""
def test_uses_default_value(self, monkeypatch: pytest.MonkeyPatch) -> None:
ini = configparser.ConfigParser()
expected = str(Path("~/.password-store").expanduser())
# no password store configured (neither per env. variable nor ini file
# option) -> default value (`~/.password-store`)
monkeypatch.delenv("PASSWORD_STORE_DIR", raising=False)
ini["example.com"] = {}
env, pwd_store_dir = passgithelper.compute_pass_environment(ini["example.com"])
assert str(pwd_store_dir) == env.get("PASSWORD_STORE_DIR")
assert pwd_store_dir == Path(expected)
# also: check `~` expansion
assert pwd_store_dir.is_absolute()
def test_uses_env_var_value(self, monkeypatch: pytest.MonkeyPatch) -> None:
ini = configparser.ConfigParser()
expected = "/tmp/password-store-from-env"
# `PASSWORD_STORE_DIR` in environment, empty ini file section -> value of
# env. variable overrides default
monkeypatch.setenv("PASSWORD_STORE_DIR", expected)
ini["example.com"] = {}
env, pwd_store_dir = passgithelper.compute_pass_environment(ini["example.com"])
assert str(pwd_store_dir) == env.get("PASSWORD_STORE_DIR")
assert pwd_store_dir == Path(expected)
def test_ini_file_option_overrides_environment(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
ini = configparser.ConfigParser()
expected = "/tmp/password-store-from-ini"
# `PASSWORD_STORE_DIR` in environemnt, `password_store_dir` in ini file
# section -> value from ini file overrides env. variable
monkeypatch.setenv("PASSWORD_STORE_DIR", "/tmp/password-store-from-env")
ini["example.com"] = {"password_store_dir": expected}
env, pwd_store_dir = passgithelper.compute_pass_environment(ini["example.com"])
assert str(pwd_store_dir) == env.get("PASSWORD_STORE_DIR")
assert pwd_store_dir == Path(expected)
def test_ignores_empty_ini_file_option(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
ini = configparser.ConfigParser()
expected = "/tmp/password-store-from-env"
# `PASSWORD_STORE_DIR` in environment, empty `password_store_dir` in ini
# file section -> empty ini value ignored, fall back to env. variable
monkeypatch.setenv("PASSWORD_STORE_DIR", expected)
ini["example.com"] = {"password_store_dir": ""}
env, pwd_store_dir = passgithelper.compute_pass_environment(ini["example.com"])
assert str(pwd_store_dir) == env.get("PASSWORD_STORE_DIR")
assert pwd_store_dir == Path(expected)
def test_ignores_empty_env_var_value(self, monkeypatch: pytest.MonkeyPatch) -> None:
ini = configparser.ConfigParser()
expected = str(Path("~/.password-store").expanduser())
# empty `PASSWORD_STORE_DIR` in environment, empty ini file section -> empty
# env. var value ignored, fall back to default
monkeypatch.setenv("PASSWORD_STORE_DIR", "")
ini["example.com"] = {}
env, pwd_store_dir = passgithelper.compute_pass_environment(ini["example.com"])
assert str(pwd_store_dir) == env.get("PASSWORD_STORE_DIR")
assert pwd_store_dir == Path(expected)
# also: check `~` expansion
assert pwd_store_dir.is_absolute()
class TestSkippingDataExtractor:
class ExtractorImplementation(passgithelper.SkippingDataExtractor):
def configure(self, config: configparser.SectionProxy) -> None:
pass
def __init__(self, skip_characters: int = 0) -> None:
super().__init__(skip_characters)
def _get_raw(
self, entry_text: Text, entry_lines: Sequence[Text] # noqa: ARG002
) -> Text | None:
return entry_lines[0]
def test_smoke(self) -> None:
extractor = self.ExtractorImplementation(4)
assert extractor.get_value("foo", ["testthis"]) == "this"
def test_too_short(self) -> None:
extractor = self.ExtractorImplementation(8)
assert extractor.get_value("foo", ["testthis"]) == ""
extractor = self.ExtractorImplementation(10)
assert extractor.get_value("foo", ["testthis"]) == ""
class TestSpecificLineExtractor:
def test_smoke(self) -> None:
extractor = passgithelper.SpecificLineExtractor(1, 6)
assert (
extractor.get_value("foo", ["line 1", "user: bar", "more lines"]) == "bar"
)
def test_no_such_line(self) -> None:
extractor = passgithelper.SpecificLineExtractor(3, 6)
assert extractor.get_value("foo", ["line 1", "user: bar", "more lines"]) is None
class TestRegexSearchExtractor:
def test_smoke(self) -> None:
extractor = passgithelper.RegexSearchExtractor("^username: (.*)$", "")
assert (
extractor.get_value(
"foo",
[
"thepassword",
"somethingelse",
"username: user",
"username: second ignored",
],
)
== "user"
)
def test_missing_group(self) -> None:
with pytest.raises(ValueError, match="must contain"):
passgithelper.RegexSearchExtractor("^username: .*$", "")
def test_configuration(self) -> None:
extractor = passgithelper.RegexSearchExtractor("^username: (.*)$", "_username")
config = configparser.ConfigParser()
config.read_string(r"""[test]
regex_username=^foo: (.*)$""")
extractor.configure(config["test"])
assert extractor._regex.pattern == r"^foo: (.*)$"
def test_configuration_checks_groups(self) -> None:
extractor = passgithelper.RegexSearchExtractor("^username: (.*)$", "_username")
config = configparser.ConfigParser()
config.read_string(r"""[test]
regex_username=^foo: .*$""")
with pytest.raises(ValueError, match="must contain"):
extractor.configure(config["test"])
class TestEntryNameExtractor:
def test_smoke(self) -> None:
assert passgithelper.EntryNameExtractor().get_value("foo/bar", []) == "bar"
class TestStaticUsernameExtractor:
def test_extracts_username_from_config(self) -> None:
config = configparser.ConfigParser()
config.read_string("""[test]
username = address@example.com
""")
extractor = passgithelper.StaticUsernameExtractor()
extractor.configure(config["test"])
assert (
extractor.get_value("any/entry", ["any", "lines"]) == "address@example.com"
)
def test_returns_none_when_no_username_configured(self) -> None:
config = configparser.ConfigParser()
config.read_string("""[test]
target = some/target
""")
extractor = passgithelper.StaticUsernameExtractor()
extractor.configure(config["test"])
assert extractor.get_value("any/entry", ["any", "lines"]) is None
def test_inherits_from_default_section(self) -> None:
config = configparser.ConfigParser()
config.read_string("""[DEFAULT]
username = default@example.com
[test]
target = some/target
""")
extractor = passgithelper.StaticUsernameExtractor()
extractor.configure(config["test"])
assert (
extractor.get_value("any/entry", ["any", "lines"]) == "default@example.com"
)
def test_section_overrides_default(self) -> None:
config = configparser.ConfigParser()
config.read_string("""[DEFAULT]
username = default@example.com
[test]
target = some/target
username = override@example.com
""")
extractor = passgithelper.StaticUsernameExtractor()
extractor.configure(config["test"])
assert (
extractor.get_value("any/entry", ["any", "lines"]) == "override@example.com"
)
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
entry_data=b"ignored",
mock_co_expect_call=False,
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_parse_mapping_file_missing() -> None:
with pytest.raises(
RuntimeError, match=r"No mapping configured so far at any XDG config location."
):
_ = passgithelper.parse_mapping(None)
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/smoke",
entry_data=b"ignored",
mock_co_expect_call=False,
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_parse_mapping_from_xdg() -> None:
config = passgithelper.parse_mapping(None)
assert "mytest.com" in config
assert config["mytest.com"]["target"] == "dev/mytest"
class TestScript:
def test_help(self, capsys: CapsysType) -> None:
with pytest.raises(SystemExit, match=r"^0$"):
passgithelper.main(["--help"])
out, err = capsys.readouterr()
assert "usage: " in out
assert not err
def test_skip(self, monkeypatch: pytest.MonkeyPatch, capsys: CapsysType) -> None:
monkeypatch.setenv("PASS_GIT_HELPER_SKIP", "1")
with pytest.raises(SystemExit, match=r"^6$"):
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert not out
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/smoke",
request="""
protocol=https
host=mytest.com""",
entry_data=b"narf",
entry_name="dev/mytest",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_smoke_resolve(self, capsys: CapsysType) -> None:
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert out == "password=narf\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
request="host=ignored",
mock_co_expect_call=False,
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_unsupported_action_option(self, caplog: CaplogType) -> None:
"""Check handling of unsupported ``action`` option."""
with pytest.raises(SystemExit, match=r"^5$"):
passgithelper.main(["store"])
assert caplog.record_tuples[-1] == (
"root",
logging.INFO,
"Action 'store' is currently not supported",
)
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/smoke",
mock_co_expect_call=False,
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_request_without_host(self, capsys: CapsysType) -> None:
"""Check handling of request without ``host``.
Note: The current handling is not optimal since the error message
indicates that the error occurs while retrieving a password store entry
instead of clearly stating that the received request is invalid.
"""
with pytest.raises(SystemExit, match=r"^3$"):
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert not out
assert "Unable to retrieve entry:" in err # TODO: check if this can be changed
assert "Request lacks host entry" in err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/smoke",
request="request_line_without_equals_sign",
mock_co_expect_call=False,
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_request_with_invalid_line(self, capsys: CapsysType) -> None:
"""Check handling of invalid request line (i.e. line which does not contain a ``=``).
Note: The current handling is not optimal since the ValueError exception
'escapes' the error handling in main(..).
"""
with pytest.raises(
ValueError,
match=r"^Missing '=' in request line, cannot be parsed as key/value pair: '.*'$",
):
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert not out
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/smoke",
request="""
protocol=https
host=mytest.com
path=/foo/bar.git""",
entry_data=b"ignored",
mock_co_expect_call=False,
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_path_used_if_present_fails(self, capsys: CapsysType) -> None:
"""Request contains `path` which does not have a corresponding section in mapping file."""
with pytest.raises(SystemExit, match=r"^3$"):
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert not out
assert "No mapping section" in err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/with-path",
request="""
protocol=https
host=mytest.com
path=subpath/bar.git""",
entry_data=b"narf",
entry_name="dev/mytest",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_path_used_if_present(self, capsys: CapsysType) -> None:
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert out == "password=narf\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/with-invalid-mapping",
request="host=ignored",
mock_co_expect_call=False,
err_expected="Unable to parse mapping file: File contains no section headers.",
),
],
indirect=True,
)
def test_invalid_mapping_file(
self, capsys: CapsysType, helper_config: HelperConfigAndMock
) -> None:
with pytest.raises(SystemExit, match=r"^4$"):
passgithelper.main(["get"])
teardown_helper_capsys_checks(capsys, helper_config.test_params)
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/wildcard",
request="""
protocol=https
host=wildcard.com
username=wildcard
path=subpath/bar.git""",
entry_data=b"narf-wildcard",
entry_name="dev/https/wildcard.com/wildcard",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_wildcard_matching(self, capsys: CapsysType) -> None:
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert out == "password=narf-wildcard\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/wildcard_path",
request="""
protocol=https
host=path_wildcard.com
username=path_wildcard
path=subpath/bar.git""",
entry_data=b"daniele-tentoni-path-wildcard",
entry_name="dev/https/path_wildcard.com/path_wildcard/subpath/bar.git",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_wildcard_path_matching(self, capsys: CapsysType) -> None:
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert out == "password=daniele-tentoni-path-wildcard\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/with-username",
request="""
host=plainline.com""",
entry_data=b"password\nusername",
entry_name="dev/plainline",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_username_provided(self, capsys: CapsysType) -> None:
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert out == "password=password\nusername=username\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/with-username",
request="""
host=plainline.com
username=narf""",
entry_data=b"password\nusername",
entry_name="dev/plainline",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_username_skipped_if_provided(self, capsys: CapsysType) -> None:
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert out == "password=password\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/with-username",
request="""
protocol=https
host=mytest.com""",
entry_data=b"narf",
entry_name="dev/mytest",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_custom_mapping_used(self, capsys: CapsysType) -> None:
# this would fail for the default file from with-username
passgithelper.main(["-m", "test_data/smoke/git-pass-mapping.ini", "get"])
out, err = capsys.readouterr()
assert out == "password=narf\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/with-username-skip",
request="""
protocol=https
host=mytest.com""",
entry_data=b"password: xyz\nuser: tester",
entry_name="dev/mytest",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_prefix_skipping(self, capsys: CapsysType) -> None:
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert out == "password=xyz\nusername=tester\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/unknown-username-extractor",
request="""
protocol=https
host=mytest.com""",
entry_data=b"ignored",
mock_co_expect_call=False,
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_select_unknown_username_extractor(self, capsys: CapsysType) -> None:
with pytest.raises(SystemExit, match=r"^3$"):
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert not out
assert "username_extractor of type 'doesntexist' does not exist" in err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/regex-username-extraction",
request="""
protocol=https
host=mytest.com""",
entry_data=b"xyz\nsomeline\nmyuser: tester\n morestuff\nmyuser: ignore",
entry_name="dev/mytest",
),
],
indirect=True,
)
@pytest.mark.usefixtures("helper_config")
def test_regex_username_selection(self, capsys: CapsysType) -> None:
passgithelper.main(["get"])
out, err = capsys.readouterr()
assert out == "password=xyz\nusername=tester\n"
assert not err
@pytest.mark.parametrize(
"helper_config",
[
HelperConfig(
xdg_dir="test_data/entry-name-extraction",
request="""
protocol=https
host=mytest.com""",