Repository navigation
Expand file tree
/
Copy pathtest_main.py
More file actions
978 lines (831 loc) · 34.8 KB
/
Copy pathtest_main.py
File metadata and controls
978 lines (831 loc) · 34.8 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
# Copyright © Michal Čihař <michal@weblate.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Test command-line interface."""
# pylint: disable=missing-function-docstring
from __future__ import annotations
import errno
import json
import os
import sys
from io import BytesIO, TextIOWrapper
from itertools import product
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from typing import TYPE_CHECKING
from unittest.mock import patch
import responses
import wlc
from wlc.config import WeblateConfig
from wlc.main import main
from .test_base import (
DATA_TEST_BASE,
TEST_CONFIG,
TEST_DATA,
TEST_SECTION,
BufferedStringIO,
CLITestBase,
)
if TYPE_CHECKING:
from collections.abc import Iterator
from wlc.client import LazyObjectT, RequestParams
class TestSettings(CLITestBase):
"""Test settings handling."""
def test_commandline(self) -> None:
"""Configuration using command-line."""
output = self.execute(["--url", "https://example.net/", "list-projects"])
self.assertIn("Hello", output)
def test_stdout(self) -> None:
"""Configuration using params."""
output = self.execute(["list-projects"], stdout=True)
self.assertIn("Hello", output)
def test_debug(self) -> None:
"""Debug mode."""
output = self.execute(["--debug", "list-projects"], stdout=True)
self.assertIn("HTTP request", output)
self.assertIn("api/projects", output)
def test_debug_redacts_authorization(self) -> None:
"""Debug mode should not leak API tokens."""
try:
os.environ["WLC_KEY"] = "KEY"
output = self.execute(["--debug", "show", "acl"], stdout=True)
self.assertIn('"Authorization": "<redacted>"', output)
self.assertNotIn("Token KEY", output)
finally:
del os.environ["WLC_KEY"]
def test_settings(self) -> None:
"""Configuration using settings param."""
output = self.execute(
["list-projects"], settings=(("weblate", "url", "https://example.net/"),)
)
self.assertIn("Hello", output)
def test_config(self) -> None:
"""Configuration using custom config file."""
output = self.execute(
["--config", str(TEST_CONFIG), "list-projects"], settings=False
)
self.assertIn("Hello", output)
def test_explicit_config_is_authoritative(self) -> None:
"""Explicit config is not overridden by repo config in cwd."""
current = Path.cwd()
with TemporaryDirectory() as tmpdirname:
explicit = Path(tmpdirname) / "explicit.ini"
explicit.write_text(
"[weblate]\nurl = http://127.0.0.1:8000/api/\n", encoding="utf-8"
)
repo = Path(tmpdirname) / "repo"
nested = repo / "nested"
nested.mkdir(parents=True)
(repo / ".weblate").write_text(
"[weblate]\nurl = http://denied.example.com/\n", encoding="utf-8"
)
try:
os.environ["WLC_KEY"] = "KEY"
os.chdir(nested)
output = self.execute(
["--config", str(explicit), "show", "acl"], settings=False
)
finally:
os.chdir(current)
if "WLC_KEY" in os.environ:
del os.environ["WLC_KEY"]
self.assertIn("ACL", output)
def test_missing_explicit_config_reports_error(self) -> None:
"""Missing explicit config path should be reported to the user."""
with TemporaryDirectory() as tmpdirname:
missing = Path(tmpdirname) / "missing.ini"
output = self.execute(
["--config", str(missing), "list-projects"], settings=False, expected=1
)
self.assertIn("Error: Could not read configuration file:", output)
self.assertIn("missing.ini", output)
def test_empty_explicit_config_reports_error_without_discovery(self) -> None:
"""An empty explicit path fails before discovery or HTTP requests."""
with (
patch.object(
WeblateConfig, "find_config", return_value=TEST_CONFIG
) as user,
patch.object(
WeblateConfig, "find_project_config", return_value=TEST_CONFIG
) as project,
):
output = self.execute(
["--config", "", "list-projects"], settings=False, expected=1
)
self.assertIn("Error: Could not read configuration file:", output)
user.assert_not_called()
project.assert_not_called()
self.assertEqual(len(responses.calls), 0)
def test_config_section(self) -> None:
"""Configuration using custom config file section."""
output = self.execute(
[
"--config",
str(TEST_SECTION),
"--config-section",
"custom",
"list-projects",
],
settings=False,
)
self.assertIn("Hello", output)
def test_config_key(self) -> None:
"""Configuration using custom config file section and key set is ignored."""
output = self.execute(
[
"--config",
str(TEST_CONFIG),
"--config-section",
"withkey",
"show",
"acl",
],
settings=False,
expected=1,
)
self.assertIn(
"Error: Using 'key' in settings is insecure, use [keys] section instead",
output,
)
def test_config_appdata(self) -> None:
"""Verify keys are loaded from the [keys] section in APPDATA-based config."""
output = self.execute(["show", "acl"], settings=False, expected=1)
self.assertIn("You don't have permission to access this object", output)
try:
os.environ["APPDATA"] = str(TEST_DATA)
output = self.execute(["show", "acl"], settings=False)
self.assertIn("ACL", output)
finally:
del os.environ["APPDATA"]
def test_env_key(self) -> None:
"""Verify WLC_KEY environment variable provides API key."""
try:
os.environ["WLC_KEY"] = "KEY"
output = self.execute(["show", "acl"], settings=False)
self.assertIn("ACL", output)
finally:
del os.environ["WLC_KEY"]
def test_env_url(self) -> None:
"""Verify WLC_URL environment variable provides API URL."""
try:
os.environ["WLC_URL"] = "https://example.net/"
output = self.execute(["list-projects"], settings=False)
self.assertIn("Hello", output)
finally:
del os.environ["WLC_URL"]
def test_config_cwd(self) -> None:
"""Test loading settings from current dir."""
current = Path.cwd()
try:
os.chdir(Path(__file__).parent / "test_data")
output = self.execute(["show"], settings=False)
self.assertIn("Weblate", output)
finally:
os.chdir(current)
def test_default_config_values(self) -> None:
"""Test default parser values."""
config = WeblateConfig()
self.assertEqual(config.get("weblate", "retries"), "0")
self.assertEqual(config.get("weblate", "timeout"), "300")
self.assertEqual(
config.get("weblate", "allowed_methods"),
"HEAD\nDELETE\nOPTIONS\nPUT\nGET",
)
self.assertEqual(config.get("weblate", "backoff_factor"), "0")
self.assertIsNone(config.get("weblate", "status_forcelist"))
def test_parsing(self) -> None:
"""Test config file parsing."""
config = WeblateConfig()
self.assertEqual(config.get("weblate", "url"), wlc.API_URL)
config.load()
config.load(TEST_CONFIG)
self.assertEqual(config.get("weblate", "url"), "https://example.net/")
self.assertEqual(config.get("weblate", "retries"), "999")
self.assertEqual(config.get("weblate", "allowed_methods"), "PUT,POST")
self.assertEqual(config.get("weblate", "backoff_factor"), "0.2")
self.assertEqual(
config.get("weblate", "status_forcelist"), "429,500,502,503,504"
)
def test_get_request_options(self) -> None:
"""Test the get_request_options method when all options are in config."""
config = WeblateConfig()
config.load()
config.load(TEST_CONFIG)
(
retries,
status_forcelist,
allowed_methods,
backoff_factor,
_timeout,
) = config.get_request_options()
self.assertEqual(retries, 999)
self.assertEqual(status_forcelist, [429, 500, 502, 503, 504])
self.assertEqual(allowed_methods, ["PUT", "POST"])
self.assertEqual(backoff_factor, 0.2)
def test_default_request_options(self) -> None:
"""Test the get_request_options method with default config values."""
config = WeblateConfig()
(
retries,
status_forcelist,
allowed_methods,
backoff_factor,
timeout,
) = config.get_request_options()
self.assertEqual(retries, 0)
self.assertIsNone(status_forcelist)
self.assertEqual(
allowed_methods,
["HEAD", "DELETE", "OPTIONS", "PUT", "GET"],
)
self.assertEqual(backoff_factor, 0.0)
self.assertEqual(timeout, 300)
def test_argv(self) -> None:
"""Test sys.argv processing."""
backup = sys.argv
try:
sys.argv = ["wlc", "version"]
output = self.execute(None)
self.assertIn(f"version: {wlc.__version__}", output)
finally:
sys.argv = backup
class TestProjectSettings(CLITestBase):
"""Test project configuration credential precedence."""
def test_project_default_unsupported_path_is_terminal_safe(self) -> None:
"""Unsupported repository defaults must produce handled diagnostics."""
current = Path.cwd()
with (
TemporaryDirectory() as tmpdirname,
patch.object(WeblateConfig, "find_config", return_value=None),
patch.dict(os.environ, {}, clear=True),
):
repo = Path(tmpdirname)
paths = (
"a/b/c/d",
"a/b/c/d\x1b]0;title\x07",
"a/b/c/d/e\x1b]52;c;cHJlZmVyZW5jZQ==\x07",
"a/b/c/d\x1b[2J",
)
try:
os.chdir(repo)
for path, command, tty in product(paths, ("ls", "show"), (False, True)):
with self.subTest(path=path, command=command, tty=tty):
(repo / ".weblate").write_text(
"[weblate]\nurl = http://127.0.0.1:8000/api/\n"
f"translation = {path}\n",
encoding="utf-8",
)
output = self.execute(
[command], settings=False, expected=1, tty=tty
)
self.assertEqual(output, "Error: Invalid object path.\n")
self.assertFalse(responses.calls)
finally:
os.chdir(current)
def test_project_default_rejects_object_path_traversal(self) -> None:
"""Repository defaults can not steer authenticated object requests."""
current = Path.cwd()
with TemporaryDirectory() as tmpdirname:
root = Path(tmpdirname)
user_config = root / "user.ini"
user_config.write_text(
"[weblate]\nurl = http://127.0.0.1:8000/api/\n"
"\n"
"[keys]\nhttp://127.0.0.1:8000/api/ = KEY\n",
encoding="utf-8",
)
repo = root / "repo"
repo.mkdir()
(repo / ".weblate").write_text(
"[weblate]\ntranslation = ../projects/hello\n", encoding="utf-8"
)
try:
os.chdir(repo)
with (
patch.object(
WeblateConfig, "find_config", return_value=user_config
),
patch.dict(os.environ, {}, clear=True),
):
for command in ("show", "delete"):
with self.subTest(command=command):
output = self.execute([command], settings=False, expected=1)
self.assertIn("Error: Invalid object path.", output)
finally:
os.chdir(current)
self.assertFalse(responses.calls)
def test_project_config_with_env_key_reports_error(self) -> None:
"""WLC_KEY can not use a URL from discovered project config."""
current = Path.cwd()
with TemporaryDirectory() as tmpdirname:
repo = Path(tmpdirname) / "repo"
repo.mkdir(parents=True)
(repo / ".weblate").write_text(
"[weblate]\nurl = http://denied.example.com/api/\n", encoding="utf-8"
)
try:
os.chdir(repo)
with (
patch.object(WeblateConfig, "find_config", return_value=None),
patch.dict(os.environ, {"WLC_KEY": "KEY"}, clear=True),
):
output = self.execute(["show", "acl"], settings=False, expected=1)
finally:
os.chdir(current)
self.assertIn(
"Error: Using WLC_KEY with project configuration requires WLC_URL.",
output,
)
def test_project_config_with_env_key_allows_env_url(self) -> None:
"""WLC_KEY can use WLC_URL even when project config is present."""
current = Path.cwd()
with TemporaryDirectory() as tmpdirname:
repo = Path(tmpdirname) / "repo"
repo.mkdir(parents=True)
(repo / ".weblate").write_text(
"[weblate]\nurl = http://denied.example.com/api/\n", encoding="utf-8"
)
try:
os.chdir(repo)
with (
patch.object(WeblateConfig, "find_config", return_value=None),
patch.dict(
os.environ,
{
"WLC_KEY": "KEY",
"WLC_URL": "http://127.0.0.1:8000/api/",
},
clear=True,
),
):
output = self.execute(["show", "acl"], settings=False)
finally:
os.chdir(current)
self.assertIn("ACL", output)
def test_project_config_with_cli_key_reports_error(self) -> None:
"""--key can not use a URL from discovered project config."""
current = Path.cwd()
with TemporaryDirectory() as tmpdirname:
repo = Path(tmpdirname) / "repo"
repo.mkdir(parents=True)
(repo / ".weblate").write_text(
"[weblate]\nurl = http://denied.example.com/api/\n", encoding="utf-8"
)
try:
os.chdir(repo)
with (
patch.object(WeblateConfig, "find_config", return_value=None),
patch.dict(os.environ, {}, clear=True),
):
output = self.execute(
["--key", "KEY", "show", "acl"],
settings=False,
expected=1,
)
finally:
os.chdir(current)
self.assertIn(
"Error: Using --key with project configuration requires --url.",
output,
)
def test_project_config_with_cli_key_allows_cli_url(self) -> None:
"""--key can use --url even when project config is present."""
current = Path.cwd()
with TemporaryDirectory() as tmpdirname:
repo = Path(tmpdirname) / "repo"
repo.mkdir(parents=True)
(repo / ".weblate").write_text(
"[weblate]\nurl = http://denied.example.com/api/\n", encoding="utf-8"
)
try:
os.chdir(repo)
with (
patch.object(WeblateConfig, "find_config", return_value=None),
patch.dict(os.environ, {}, clear=True),
):
output = self.execute(
[
"--key",
"KEY",
"--url",
"http://127.0.0.1:8000/api/",
"show",
"acl",
],
settings=False,
)
finally:
os.chdir(current)
self.assertIn("ACL", output)
class TestCommands(CLITestBase):
"""Individual command tests."""
def test_version_bare(self) -> None:
"""Test version printing."""
output = self.execute(["version", "--bare"])
self.assertEqual(f"{wlc.__version__}\n", output)
def test_ls(self) -> None:
"""Project listing."""
output = self.execute(["ls"])
self.assertIn("Hello", output)
output = self.execute(["ls", "hello"])
self.assertIn("Weblate", output)
output = self.execute(["ls", "empty"])
self.assertEqual("", output)
def test_listing_commands_stream(self) -> None:
"""Each listing command writes a row before advancing its API iterator."""
# Use complete rows so JSON does not need unrelated lazy-object fixtures.
translation = json.loads(
(DATA_TEST_BASE / "translations-hello-weblate-cs").read_text(
encoding="utf-8"
)
)
for path in ("translations/", "components/hello/weblate/translations/"):
responses.replace(
responses.GET,
f"http://127.0.0.1:8000/api/{path}",
json={"next": None, "results": [translation]},
)
change = json.loads(
(DATA_TEST_BASE / "projects-hello-changes").read_text(encoding="utf-8")
)["results"][0]
change["component"] = None
responses.replace(
responses.GET,
"http://127.0.0.1:8000/api/projects/hello/changes/",
json={"next": None, "results": [change]},
)
commands = (
["list-projects"],
["list-components"],
["list-components", "hello"],
["list-languages"],
["list-translations"],
["list-translations", "hello/weblate"],
["list-units", "hello/weblate/cs"],
["ls"],
["ls", "hello"],
["ls", "hello/weblate"],
["changes", "hello"],
["stats", "hello/weblate"],
)
for format_name in ("text", "csv", "html", "json"):
for command in commands:
with self.subTest(format=format_name, command=command):
self.check_listing_command_stream(command, format_name)
def check_listing_command_stream(
self, command: list[str], format_name: str
) -> None:
"""Observe row delivery through a command's real API iterator."""
original = wlc.Weblate.list_factory
output = BufferedStringIO()
emitted = []
def listing(
client: wlc.Weblate,
path: str,
parser: type[LazyObjectT],
*,
params: RequestParams | None = None,
) -> Iterator[LazyObjectT]:
for row in original(client, path, parser, params=params):
previous = output.tell()
yield row
self.assertGreater(output.tell(), previous)
emitted.append(row)
with patch.object(wlc.Weblate, "list_factory", listing):
result = main(
args=["--format", format_name, *command],
settings=(),
stdout=output,
)
self.assertEqual(result, 0)
self.assertTrue(emitted)
def test_ls_leaf_legacy_behavior(self) -> None:
"""Streaming should not change the legacy leaf-listing behavior."""
for path in ("hello/weblate/cs", "123"):
with (
self.subTest(path=path),
self.assertRaisesRegex(AttributeError, "keys"),
):
self.execute(["ls", path])
def test_list_languages(self) -> None:
"""Language listing."""
output = self.execute(["list-languages"])
self.assertIn("Turkish", output)
def test_list_projects(self) -> None:
"""Project listing."""
output = self.execute(["list-projects"])
self.assertIn("Hello", output)
def test_list_components(self) -> None:
"""Components listing."""
output = self.execute(["list-components"])
self.assertIn("/hello/weblate", output)
output = self.execute(["list-components", "hello"])
self.assertIn("/hello/weblate", output)
output = self.execute(["list-components", "hello/weblate"], expected=1)
self.assertIn("This command is supported only at project level", output)
def test_list_translations(self) -> None:
"""Translations listing."""
output = self.execute(["list-translations"])
self.assertIn("/hello/weblate/cs/", output)
output = self.execute(["list-translations", "hello/weblate"])
self.assertIn("/hello/weblate/cs/", output)
output = self.execute(["list-translations", "hello/weblate"])
self.assertIn("/hello/weblate/cs/", output)
output = self.execute(
["--format", "json", "list-translations", "hello/weblate"]
)
self.assertIn("/hello/weblate/cs/", output)
def test_show(self) -> None:
"""Project show."""
output = self.execute(["show", "hello"])
self.assertIn("Hello", output)
output = self.execute(["show", "hello/weblate"])
self.assertIn("Weblate", output)
output = self.execute(["show", "hello/weblate/cs"])
self.assertIn("/hello/weblate/cs/", output)
def test_show_error(self) -> None:
self.execute(["show", "io"], expected=10)
with self.assertRaises(RuntimeError):
self.execute(["show", "bug"])
def test_invalid_server_timestamp_does_not_reach_terminal(self) -> None:
"""Malformed API dates should be handled without terminal controls."""
payload = "\x1b]8;;https://evil.example\x07CLICK-ME\x1b]8;;\x07"
for command, path, fixture in (
(
["show", "hello/weblate/cs"],
"translations/hello/weblate/cs",
"translations-hello-weblate-cs",
),
(
["stats", "hello"],
"projects/hello/statistics",
"projects-hello-statistics",
),
):
with self.subTest(command=command):
data = json.loads((TEST_DATA / "api" / fixture).read_text())
data["last_change"] = payload
responses.replace(
responses.GET,
f"http://127.0.0.1:8000/api/{path}/",
json=data,
)
output = self.execute(command, expected=1, tty=True)
self.assertIn("Error: Invalid last_change timestamp", output)
self.assertNotIn("Traceback", output)
self.assertNotIn("\x1b", output)
self.assertNotIn("evil.example", output)
def test_delete(self) -> None:
"""Project delete."""
output = self.execute(["delete", "hello"])
self.assertEqual("", output)
output = self.execute(["delete", "hello/weblate"])
self.assertEqual("", output)
output = self.execute(["delete", "hello/weblate/cs"])
self.assertEqual("", output)
class TestRepositoryCommands(CLITestBase):
"""Test repository management commands."""
def test_commit(self) -> None:
"""Project commit."""
output = self.execute(["commit", "hello"])
self.assertEqual("", output)
output = self.execute(["commit", "hello/weblate"])
self.assertEqual("", output)
output = self.execute(["commit", "hello/weblate/cs"])
self.assertEqual("", output)
def test_push(self) -> None:
"""Project push."""
msg = "Error: Failed to push changes!\nPush is disabled for Hello/Weblate.\n"
output = self.execute(["push", "hello"], expected=1)
self.assertEqual(msg, output)
output = self.execute(["push", "hello/weblate"], expected=1)
self.assertEqual(msg, output)
output = self.execute(["push", "hello/weblate/cs"], expected=1)
self.assertEqual(msg, output)
def test_pull(self) -> None:
"""Project pull."""
output = self.execute(["pull", "hello"])
self.assertEqual("", output)
output = self.execute(["pull", "hello/weblate"])
self.assertEqual("", output)
output = self.execute(["pull", "hello/weblate/cs"])
self.assertEqual("", output)
def test_reset(self) -> None:
"""Project reset."""
output = self.execute(["reset", "hello"])
self.assertEqual("", output)
output = self.execute(["reset", "hello/weblate"])
self.assertEqual("", output)
output = self.execute(["reset", "hello/weblate/cs"])
self.assertEqual("", output)
def test_cleanup(self) -> None:
"""Project cleanup."""
output = self.execute(["cleanup", "hello"])
self.assertEqual("", output)
output = self.execute(["cleanup", "hello/weblate"])
self.assertEqual("", output)
output = self.execute(["cleanup", "hello/weblate/cs"])
self.assertEqual("", output)
def test_repo(self) -> None:
"""Project repo."""
output = self.execute(["repo", "hello"])
self.assertIn("needs_commit", output)
output = self.execute(["repo", "hello/weblate"])
self.assertIn("needs_commit", output)
output = self.execute(["repo", "hello/weblate/cs"])
self.assertIn("needs_commit", output)
def test_stats(self) -> None:
"""Project stats."""
output = self.execute(["stats", "hello"])
self.assertIn("translated_percent", output)
output = self.execute(["stats", "hello/weblate"])
self.assertIn("failing_percent", output)
output = self.execute(["stats", "hello/weblate/cs"])
self.assertIn("failing_percent", output)
def test_locks(self) -> None:
"""Project locks."""
output = self.execute(["lock-status", "hello"], expected=1)
self.assertIn("This command is supported only at component level", output)
output = self.execute(["lock-status", "hello/weblate"])
self.assertIn("locked", output)
output = self.execute(["lock", "hello/weblate"])
self.assertEqual("", output)
output = self.execute(["unlock", "hello/weblate"])
self.assertEqual("", output)
output = self.execute(["lock-status", "hello/weblate/cs"], expected=1)
self.assertIn("This command is supported only at component level", output)
def test_lock_status_rejects_terminal_control_response(self) -> None:
"""Malformed lock status must produce a terminal-safe diagnostic."""
payload = "\x1b]52;c;YXR0YWNrZXI=\x07"
responses.replace(
responses.GET,
"http://127.0.0.1:8000/api/components/hello/weblate/lock/",
json=[{payload: "value"}],
)
output = self.execute(["lock-status", "hello/weblate"], expected=1, tty=True)
self.assertEqual(output, "Error: Server returned an invalid lock status.\n")
self.assertNotIn("Traceback", output)
self.assertNotIn("\x1b", output)
def test_changes(self) -> None:
"""Project changes."""
output = self.execute(["changes", "hello"])
self.assertIn("action_name", output)
output = self.execute(["changes", "hello/weblate"])
self.assertIn("action_name", output)
output = self.execute(["changes", "hello/weblate/cs"])
self.assertIn("action_name", output)
class TestFileCommands(CLITestBase):
"""Test translation file transfer commands."""
def test_download(self) -> None:
"""Translation file downloads."""
output = self.execute(["download"], expected=1)
self.assertIn("Output is needed", output)
with TemporaryDirectory() as tmpdirname:
self.execute(["download", "--output", tmpdirname])
output = self.execute(["download", "hello/weblate/cs"])
self.assertIn(b"Plural-Forms:", output)
output = self.execute(
["download", "hello/weblate/cs"], stdout=True, expected=1, tty=True
)
self.assertIn("Refusing to write downloaded file to terminal", output)
output = self.execute(["download", "hello/weblate/cs", "--convert", "csv"])
self.assertIn(b'"location"', output)
with NamedTemporaryFile() as handle:
handle.close()
self.execute(["download", "hello/weblate/cs", "-o", handle.name])
output = Path(handle.name).read_bytes()
self.assertIn(b"Plural-Forms:", output)
output = self.execute(["download", "hello/weblate"], expected=1)
self.assertIn("Output is needed", output)
with TemporaryDirectory() as tmpdirname:
self.execute(["download", "hello/weblate", "--output", tmpdirname])
output = self.execute(["download", "hello"], expected=1)
self.assertIn("Output is needed", output)
with TemporaryDirectory() as tmpdirname:
self.execute(["download", "hello", "--no-glossary", "--output", tmpdirname])
# The hello-android should not be present as it is flagged as a glossary
self.assertEqual(
[path.name for path in Path(tmpdirname).iterdir()],
["hello-weblate.zip"],
)
with TemporaryDirectory() as tmpdirname:
self.execute(
[
"download",
"hello",
"--convert",
"zip",
"--output",
str(Path(tmpdirname) / "output"),
]
)
self.assertEqual(
[path.name for path in Path(tmpdirname).iterdir()], ["output"]
)
def test_download_config(self) -> None:
with TemporaryDirectory() as tmpdirname:
self.execute(
[
"--config",
str(TEST_CONFIG),
"--config-section",
"withcomponent",
"download",
"--output",
tmpdirname,
],
settings=False,
)
self.assertEqual(
[path.name for path in Path(tmpdirname).iterdir()],
["hello-weblate.zip"],
)
with TemporaryDirectory() as tmpdirname:
self.execute(
[
"--config",
str(TEST_CONFIG),
"--config-section",
"withproject",
"download",
"--output",
tmpdirname,
],
settings=False,
)
self.assertEqual(
{path.name for path in Path(tmpdirname).iterdir()},
{"hello-weblate.zip", "hello-android.zip"},
)
def test_upload(self) -> None:
"""Translation file uploads."""
msg = "Error: Failed to upload translations!\nNot found.\n"
output = self.execute(["upload", "hello/weblate"], expected=1)
self.assertEqual(
"Error: This command is supported only at translation level\n", output
)
with self.get_text_io_wrapper("test upload data") as stdin:
output = self.execute(["upload", "hello/weblate/cs"], stdin=stdin)
self.assertEqual("", output)
with self.get_text_io_wrapper("wrong upload data") as stdin:
output = self.execute(
["upload", "hello/weblate/cs"], stdin=stdin, expected=1
)
self.assertEqual(msg, output)
with NamedTemporaryFile(delete=False) as handle:
handle.write(b"test upload overwrite")
handle.close()
output = self.execute(
["upload", "hello/weblate/cs", "-i", handle.name, "--overwrite"]
)
self.assertEqual("", output)
with TemporaryDirectory() as tmpdirname:
missing = Path(tmpdirname) / "missing.po"
output = self.execute(
["upload", "hello/weblate/cs", "-i", str(missing)], expected=1
)
missing_error = FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), str(missing)
)
self.assertEqual(f"Error: {missing_error}\n", output)
@staticmethod
def get_text_io_wrapper(string: str) -> TextIOWrapper[BytesIO]:
"""Create a text io wrapper from a string."""
return TextIOWrapper(BytesIO(string.encode()), "utf8")
class TestUnitCommands(CLITestBase):
"""Test unit management commands."""
def test_list_units(self) -> None:
"""Unit listing."""
output = self.execute(["list-units", "hello/weblate/cs"])
self.assertIn("id", output)
output = self.execute(
["list-units", "hello/weblate/cs", "--query", 'source:="mr"']
)
self.assertIn("117", output)
output = self.execute(["list-units", "hello/weblate"], expected=1)
self.assertIn("This command is supported only at translation level", output)
def test_show_unit(self) -> None:
"""Unit show."""
output = self.execute(["show", "123"])
self.assertIn("123", output)
self.assertIn("source", output)
def test_delete_unit(self) -> None:
"""Unit delete."""
output = self.execute(["delete", "123"])
self.assertEqual("", output)
def test_edit_unit(self) -> None:
"""Unit edit."""
output = self.execute(["edit-unit", "123", "--target", "foo", "--state", "30"])
self.assertEqual("", output)
output = self.execute(["edit-unit", "hello/weblate/cs"], expected=1)
self.assertIn("This command is supported only at unit level", output)
output = self.execute(["edit-unit", "123"], expected=1)
self.assertIn("No changes specified", output)
class TestErrors(CLITestBase):
"""Error handling tests."""
def test_commandline_missing_key(self) -> None:
"""Configuration using command-line."""
output = self.execute(
["--url", "http://denied.example.com", "list-projects"], expected=1
)
self.assertIn("Missing API key", output)