py-jsync 1.0.6__tar.gz → 1.0.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -40,5 +40,8 @@ jobs:
40
40
  - name: Ruff
41
41
  run: uv run ruff check .
42
42
 
43
+ - name: Test
44
+ run: uv run pytest
45
+
43
46
  - name: Build
44
47
  run: uv build
@@ -0,0 +1,5 @@
1
+ dist
2
+ .venv
3
+ .pytest_cache
4
+ .coverage
5
+ htmlcov
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: py-jsync
3
- Version: 1.0.6
3
+ Version: 1.0.7
4
4
  Summary: Tool to run rsync utility in parallel
5
5
  Author-email: Vladimir Grebenshchikov <vova@zote.me>
6
6
  License-File: LICENSE
@@ -8,6 +8,8 @@ Requires-Python: >=3.10
8
8
  Requires-Dist: humanize<5,>=4.9
9
9
  Requires-Dist: rich<15,>=14.0
10
10
  Provides-Extra: dev
11
+ Requires-Dist: pytest-cov>=6; extra == 'dev'
12
+ Requires-Dist: pytest>=8.3; extra == 'dev'
11
13
  Requires-Dist: ruff>=0.9.9; extra == 'dev'
12
14
  Description-Content-Type: text/markdown
13
15
 
@@ -12,6 +12,8 @@ dependencies = [
12
12
 
13
13
  [project.optional-dependencies]
14
14
  dev = [
15
+ "pytest>=8.3",
16
+ "pytest-cov>=6",
15
17
  "ruff>=0.9.9",
16
18
  ]
17
19
 
@@ -56,3 +58,10 @@ max-complexity = 15
56
58
 
57
59
  [tool.ruff.format]
58
60
  quote-style = "preserve"
61
+
62
+ [tool.pytest.ini_options]
63
+ testpaths = ["tests"]
64
+ addopts = [
65
+ "--cov=jsync",
66
+ "--cov-report=term-missing",
67
+ ]
@@ -0,0 +1,72 @@
1
+ """Small stand-ins for asyncio subprocess pipes used by RSync."""
2
+
3
+
4
+ class FakePipe:
5
+ def __init__(self):
6
+ self.closed = False
7
+
8
+ def close(self):
9
+ self.closed = True
10
+
11
+
12
+ class FakeTransport:
13
+ def __init__(self):
14
+ self.pipes = {1: FakePipe(), 2: FakePipe()}
15
+
16
+ def get_pipe_transport(self, fd):
17
+ return self.pipes[fd]
18
+
19
+
20
+ class FakeStdin:
21
+ def __init__(self):
22
+ self.data = bytearray()
23
+ self.closed = False
24
+
25
+ def write(self, data):
26
+ self.data.extend(data)
27
+
28
+ async def drain(self):
29
+ return None
30
+
31
+ def close(self):
32
+ self.closed = True
33
+
34
+
35
+ class FakeStream:
36
+ def __init__(self, reads=None, lines=None):
37
+ self._reads = list(reads or [])
38
+ self._lines = list(lines or [])
39
+
40
+ async def read(self, n=4096):
41
+ if not self._reads:
42
+ return b""
43
+ return self._reads.pop(0)
44
+
45
+ async def readline(self):
46
+ if not self._lines:
47
+ return b""
48
+ return self._lines.pop(0)
49
+
50
+
51
+ class FakeProc:
52
+ def __init__(self, stdout_lines=None, stderr_chunks=None, stdout_chunks=None, returncode=0):
53
+ self.stdout = FakeStream(reads=stdout_chunks, lines=stdout_lines)
54
+ self.stderr = FakeStream(reads=stderr_chunks)
55
+ self.stdin = FakeStdin()
56
+ self.returncode = returncode
57
+ self._transport = FakeTransport()
58
+ self.waited = False
59
+
60
+ async def wait(self):
61
+ self.waited = True
62
+ return self.returncode
63
+
64
+
65
+ def install_subprocess(monkeypatch, proc):
66
+ async def create(*args, **kwargs):
67
+ create.args = args
68
+ create.kwargs = kwargs
69
+ return proc
70
+
71
+ monkeypatch.setattr("jsync.rsync.asyncio.create_subprocess_exec", create)
72
+ return create
@@ -0,0 +1,38 @@
1
+ from types import SimpleNamespace
2
+
3
+ from rich.text import Text
4
+
5
+ from jsync.columns import FlexiColumn
6
+
7
+
8
+ def _task():
9
+ return SimpleNamespace(completed=4, total=10)
10
+
11
+
12
+ def test_flexi_column_renders_markup():
13
+ column = FlexiColumn(lambda task: f"{task.completed}/{task.total}", style="cyan")
14
+
15
+ text = column.render(_task())
16
+
17
+ assert isinstance(text, Text)
18
+ assert text.plain == "4/10"
19
+
20
+
21
+ def test_flexi_column_renders_plain_text_and_highlighter():
22
+ seen = {}
23
+
24
+ class Marker:
25
+ def highlight(self, text):
26
+ seen["text"] = text.plain
27
+
28
+ column = FlexiColumn(
29
+ lambda task: "plain",
30
+ markup=False,
31
+ highlighter=Marker(),
32
+ justify="right",
33
+ )
34
+
35
+ text = column.render(_task())
36
+
37
+ assert text.plain == "plain"
38
+ assert seen["text"] == "plain"
@@ -0,0 +1,39 @@
1
+ import importlib.metadata as importlib_metadata
2
+
3
+ import jsync
4
+
5
+
6
+ def test_public_api():
7
+ assert jsync.__all__ == ["RSync", "Syncer", "synchronize"]
8
+ assert jsync.__version__
9
+
10
+
11
+ def test_version_uses_distribution_name(monkeypatch):
12
+ def version(dist):
13
+ if dist == "py-jsync":
14
+ return "1.2.3"
15
+ raise importlib_metadata.PackageNotFoundError
16
+
17
+ monkeypatch.setattr(jsync.importlib_metadata, "version", version)
18
+
19
+ assert jsync._get_version() == "1.2.3"
20
+
21
+
22
+ def test_version_falls_back_to_import_package_name(monkeypatch):
23
+ def version(dist):
24
+ if dist == "jsync":
25
+ return "9.9.9"
26
+ raise importlib_metadata.PackageNotFoundError
27
+
28
+ monkeypatch.setattr(jsync.importlib_metadata, "version", version)
29
+
30
+ assert jsync._get_version() == "9.9.9"
31
+
32
+
33
+ def test_version_fallback_when_package_is_not_installed(monkeypatch):
34
+ def version(dist):
35
+ raise importlib_metadata.PackageNotFoundError
36
+
37
+ monkeypatch.setattr(jsync.importlib_metadata, "version", version)
38
+
39
+ assert jsync._get_version() == "0.0.0"
@@ -0,0 +1,178 @@
1
+ import asyncio
2
+ from unittest.mock import MagicMock
3
+
4
+ import pytest
5
+
6
+ from jsync.job import Job
7
+ from jsync.rsync import RSync
8
+
9
+
10
+ def make_job(files=None, total_size=0, rsync=None):
11
+ progress = MagicMock()
12
+ progress.add_task.return_value = 7
13
+ job = Job(
14
+ id=3,
15
+ files=files if files is not None else [],
16
+ progress=progress,
17
+ rsync=rsync or RSync("/data/photos", "/backup"),
18
+ callback=MagicMock(),
19
+ total_size=total_size,
20
+ )
21
+ return job
22
+
23
+
24
+ def test_start_announces_command_and_seeds_total():
25
+ job = make_job(files=["a"], total_size=2048)
26
+
27
+ job.start()
28
+
29
+ assert job.running is True
30
+ assert job.active() is True
31
+ assert job.total == 2048
32
+ job.progress.start_task.assert_called_once_with(job.task)
33
+ job.progress.update.assert_called_once_with(job.task, total=2048, completed=0, rate=0)
34
+ job.callback.assert_called_once_with(0, job)
35
+ message = job.progress.console.print.call_args.args[0]
36
+ assert "Starting job #3" in message
37
+ assert "in 1 files" in message
38
+
39
+
40
+ def test_start_without_known_total_does_not_seed_progress():
41
+ job = make_job(files=["a"], total_size=0)
42
+
43
+ job.start()
44
+
45
+ job.progress.update.assert_not_called()
46
+ job.callback.assert_not_called()
47
+
48
+
49
+ def test_process_progress_uses_itemize_total_and_reports_delta():
50
+ job = make_job(total_size=5000)
51
+ job.size = 1000
52
+
53
+ job.process_progress(
54
+ " 4538368 100% 136.61kB/s 0:00:32 (xfr#554, to-chk=0/557)"
55
+ )
56
+
57
+ assert job.size == 4538368
58
+ assert job.percent == 100
59
+ assert job.total == 5000
60
+ assert job.rate == pytest.approx(136.61 * 1000)
61
+ job.callback.assert_called_once_with(4538368 - 1000, job)
62
+ update = job.progress.update.call_args.kwargs
63
+ assert update["total"] == 5000
64
+ assert update["completed"] == 4538368
65
+ assert update["rate"] == job.rate
66
+
67
+
68
+ def test_process_progress_estimates_from_file_count_under_ten_percent():
69
+ job = make_job(total_size=0)
70
+
71
+ job.process_progress(
72
+ " 1000 0% 4.73MB/s 1:05:31 (xfr#2, to-chk=8/10)"
73
+ )
74
+
75
+ # 2/10 files -> 20%, so the displayed total is size * 100 / 20.
76
+ assert job.percent == 0
77
+ assert job.progress.update.call_args.kwargs["total"] == 5000
78
+ job.callback.assert_called_once_with(1000, job)
79
+
80
+
81
+ def test_process_progress_estimates_total_from_percent():
82
+ job = make_job(total_size=0)
83
+
84
+ job.process_progress(" 2500 25% 1kB/s 0:00:01")
85
+
86
+ assert job.progress.update.call_args.kwargs["total"] == 10000
87
+ assert job.percent == 25
88
+ assert job.rate == 1000
89
+
90
+
91
+ def test_process_progress_keeps_zero_delta_until_there_is_movement():
92
+ job = make_job(total_size=0)
93
+
94
+ job.process_progress(" 0 0% 0B/s 0:00:00")
95
+
96
+ assert job.size == 0
97
+ job.callback.assert_called_once_with(None, job)
98
+
99
+
100
+ def test_process_progress_ignores_malformed_lines():
101
+ job = make_job()
102
+
103
+ job.process_progress("12 5%")
104
+ job.process_progress(" 12 xx% bad 0:00:00")
105
+
106
+ job.progress.update.assert_not_called()
107
+ job.callback.assert_not_called()
108
+ assert job.file == ""
109
+
110
+
111
+ def test_process_progress_prints_current_filename():
112
+ job = make_job()
113
+
114
+ job.process_progress("folder/IMG_7440.xmp")
115
+
116
+ assert job.file == "folder/IMG_7440.xmp"
117
+ job.progress.console.print.assert_called_once()
118
+ job.progress.update.assert_called_once_with(job.task, filename="folder/IMG_7440.xmp")
119
+
120
+
121
+ def test_process_error_prints_complete_lines_and_keeps_a_partial():
122
+ job = make_job()
123
+
124
+ job.process_error("disk ")
125
+ job.process_error("full\nnext")
126
+
127
+ assert job.error_buf == "next"
128
+ printed = job.progress.console.print.call_args.args[0]
129
+ assert "disk full" in printed
130
+ assert "3" in printed
131
+
132
+ job.process_error(" line\n")
133
+
134
+ assert job.error_buf == ""
135
+ assert job.progress.console.print.call_count == 2
136
+
137
+
138
+ def test_transfer_skips_empty_file_list():
139
+ job = make_job(files=[])
140
+ job.rsync.transfer = MagicMock()
141
+
142
+ asyncio.run(job.transfer())
143
+
144
+ job.rsync.transfer.assert_not_called()
145
+ message = job.progress.console.print.call_args.args[0]
146
+ assert "Nothing to do" in message
147
+
148
+
149
+ def test_transfer_marks_job_done():
150
+ job = make_job(files=["a.txt"])
151
+
152
+ async def transfer(files, progress_callback, error_callback):
153
+ progress_callback("a.txt")
154
+ error_callback("warn\n")
155
+ return None
156
+
157
+ job.rsync.transfer = transfer
158
+
159
+ asyncio.run(job.transfer())
160
+
161
+ job.progress.update.assert_called_with(job.task, filename="done", rate=None, eta="")
162
+
163
+
164
+ def test_transfer_records_failure_and_reraises():
165
+ job = make_job(files=["a.txt"])
166
+
167
+ async def transfer(files, progress_callback, error_callback):
168
+ raise RuntimeError("rsync failed")
169
+
170
+ job.rsync.transfer = transfer
171
+
172
+ with pytest.raises(RuntimeError, match="rsync failed"):
173
+ asyncio.run(job.transfer())
174
+
175
+ update = job.progress.update.call_args.kwargs
176
+ assert "rsync failed" in update["filename"]
177
+ assert update["eta"] == "-failed-"
178
+ assert update["rate"] is None
@@ -0,0 +1,157 @@
1
+ import asyncio
2
+ import sys
3
+
4
+ import pytest
5
+
6
+ from jsync.jsync import main, synchronize
7
+
8
+
9
+ class RecordingSyncer:
10
+ instances = []
11
+
12
+ def __init__(self, jobs_num, rsync):
13
+ self.jobs_num = jobs_num
14
+ self.rsync = rsync
15
+ self.itemize_called = False
16
+ self.transfer_called = False
17
+ self.fail = False
18
+ RecordingSyncer.instances.append(self)
19
+
20
+ def __enter__(self):
21
+ return self
22
+
23
+ def __exit__(self, exc_type, exc, tb):
24
+ return False
25
+
26
+ async def itemize(self):
27
+ self.itemize_called = True
28
+
29
+ async def transfer(self):
30
+ self.transfer_called = True
31
+ if self.fail:
32
+ raise RuntimeError("transfer failed")
33
+
34
+
35
+ @pytest.fixture
36
+ def syncer(monkeypatch):
37
+ RecordingSyncer.instances.clear()
38
+ monkeypatch.setattr("jsync.jsync.Syncer", RecordingSyncer)
39
+ return RecordingSyncer
40
+
41
+
42
+ def test_main_runs_sync_with_parallel_jobs(syncer):
43
+ asyncio_argv = ["-av", "-j", "4", "src", "dst"]
44
+
45
+ asyncio_run(main(asyncio_argv))
46
+
47
+ job = syncer.instances[-1]
48
+ assert job.jobs_num == 4
49
+ assert job.itemize_called
50
+ assert job.transfer_called
51
+ assert job.rsync.args == ["src", "dst"]
52
+ assert "-av" in job.rsync.opts
53
+ assert job.rsync.debug is False
54
+
55
+
56
+ def test_main_accepts_jobs_forms(syncer):
57
+ asyncio_run(main(["--jobs", "8", "src", "dst"]))
58
+ assert syncer.instances[-1].jobs_num == 8
59
+
60
+ asyncio_run(main(["--jobs=3", "-a", "src", "dst"]))
61
+ assert syncer.instances[-1].jobs_num == 3
62
+ assert syncer.instances[-1].rsync.opts == ["-a"]
63
+
64
+ asyncio_run(main(["-j2", "src", "dst"]))
65
+ assert syncer.instances[-1].jobs_num == 2
66
+
67
+
68
+ def test_main_enables_debug(syncer):
69
+ asyncio_run(main(["--debug", "src", "dst"]))
70
+
71
+ job = syncer.instances[-1]
72
+ assert job.rsync.debug is True
73
+ assert job.rsync.args == ["src", "dst"]
74
+ assert job.jobs_num == 6
75
+
76
+
77
+ @pytest.mark.parametrize("argv", [["--help"], ["-h"], ["-j"], ["-j", "nope"], ["only-one"]])
78
+ def test_main_usage_exits(syncer, capsys, argv):
79
+ with pytest.raises(SystemExit) as exc:
80
+ asyncio_run(main(argv))
81
+
82
+ assert exc.value.code == 1
83
+ assert "USAGE" in capsys.readouterr().err
84
+ assert syncer.instances == []
85
+
86
+
87
+ def test_main_reports_transfer_error(monkeypatch, capsys):
88
+ class Failing(RecordingSyncer):
89
+ async def transfer(self):
90
+ self.transfer_called = True
91
+ raise RuntimeError("transfer failed")
92
+
93
+ monkeypatch.setattr("jsync.jsync.Syncer", Failing)
94
+
95
+ asyncio_run(main(["src", "dst"]))
96
+
97
+ err = capsys.readouterr().err
98
+ assert "Error: transfer failed" in err
99
+ assert "Traceback" not in err
100
+
101
+
102
+ def test_main_reports_traceback_when_verbose(monkeypatch, capsys):
103
+ class Failing(RecordingSyncer):
104
+ async def transfer(self):
105
+ raise RuntimeError("transfer failed")
106
+
107
+ monkeypatch.setattr("jsync.jsync.Syncer", Failing)
108
+
109
+ asyncio_run(main(["-av", "src", "dst"]))
110
+
111
+ err = capsys.readouterr().err
112
+ assert "Error: transfer failed" in err
113
+ assert "Traceback" in err
114
+ assert "RuntimeError" in err
115
+
116
+
117
+ def test_synchronize_uses_explicit_arguments(monkeypatch):
118
+ seen = {}
119
+
120
+ async def fake_main(argv):
121
+ seen["argv"] = list(argv)
122
+
123
+ monkeypatch.setattr("jsync.jsync.main", fake_main)
124
+
125
+ synchronize("src", "dst")
126
+
127
+ assert seen["argv"] == ["src", "dst"]
128
+
129
+
130
+ def test_synchronize_defaults_to_sys_argv(monkeypatch):
131
+ seen = {}
132
+
133
+ async def fake_main(argv):
134
+ seen["argv"] = list(argv)
135
+
136
+ monkeypatch.setattr("jsync.jsync.main", fake_main)
137
+ monkeypatch.setattr(sys, "argv", ["jsync", "--jobs=2", "a", "b"])
138
+
139
+ synchronize()
140
+
141
+ assert seen["argv"] == ["--jobs=2", "a", "b"]
142
+
143
+
144
+ def test_synchronize_swallows_keyboard_interrupt(monkeypatch, capsys):
145
+ def raise_interrupt(coro):
146
+ coro.close()
147
+ raise KeyboardInterrupt
148
+
149
+ monkeypatch.setattr("jsync.jsync.asyncio.run", raise_interrupt)
150
+
151
+ synchronize("src", "dst")
152
+
153
+ assert capsys.readouterr().err.strip() == "Interrupted"
154
+
155
+
156
+ def asyncio_run(coro):
157
+ return asyncio.run(coro)