| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147 |
- import io
- from pathlib import Path
- import pytest
- from tools import remote_transfer as transfer
- class LocalRemote:
- def __init__(self,fail_operation=None,fail_index=2):
- self.fail_operation=fail_operation;self.fail_index=fail_index;self.calls=[]
- def request(self,request,source=None,chunk=None,destination=None):
- self.calls.append(request.copy())
- index=request.get('index',request.get('chunk',{}).get('index'))
- if request['operation']==self.fail_operation and index==self.fail_index:
- raise transfer.TransferError('injected disconnect',255)
- data=io.BytesIO()
- if source:
- with Path(source).open('rb') as stream:
- stream.seek(chunk['offset']);data=io.BytesIO(stream.read(chunk['size']))
- output=io.BytesIO()
- result=transfer.serve(request,data,output)
- if destination:Path(destination).write_bytes(output.getvalue())
- return result
- def fixture(tmp_path,monkeypatch):
- monkeypatch.setattr(transfer,'REMOTE_ROOT',tmp_path)
- source=tmp_path/'source with spaces.bin'
- source.write_bytes(bytes(range(256))*1024+b'final bytes')
- return source,transfer.describe(source,transfer.MIN_CHUNK)
- def test_upload_resumes_only_missing_or_corrupt_chunks(tmp_path,monkeypatch):
- source,manifest=fixture(tmp_path,monkeypatch);dest=tmp_path/'destination.bin'
- broken=LocalRemote('put')
- with pytest.raises(transfer.TransferError,match='disconnect'):
- transfer.upload(broken,source,str(dest),transfer.MIN_CHUNK)
- assert not dest.exists()
- stage=transfer.stage_path(dest,manifest['sha256'],transfer.MIN_CHUNK)
- transfer.part_path(stage,0).write_bytes(b'corrupt')
- remote=LocalRemote();result=transfer.upload(remote,source,str(dest),transfer.MIN_CHUNK)
- assert result['transferred_chunks']==[0,2,3,4] and result['reused_chunks']==[1]
- assert dest.read_bytes()==source.read_bytes() and not stage.exists()
- assert [x['index'] for x in remote.calls if x['operation']=='put']==[0,2,3,4]
- def test_download_resumes_only_missing_or_corrupt_chunks(tmp_path,monkeypatch):
- source,manifest=fixture(tmp_path,monkeypatch);dest=tmp_path/'download.bin'
- with pytest.raises(transfer.TransferError,match='disconnect'):
- transfer.download(LocalRemote('get'),str(source),dest,manifest['sha256'],transfer.MIN_CHUNK)
- assert not dest.exists()
- stage=transfer.stage_path(dest,manifest['sha256'],transfer.MIN_CHUNK)
- transfer.part_path(stage,0).write_bytes(b'corrupt')
- remote=LocalRemote()
- result=transfer.download(remote,str(source),dest,manifest['sha256'],transfer.MIN_CHUNK)
- assert result['transferred_chunks']==[0,2,3,4] and result['reused_chunks']==[1]
- assert dest.read_bytes()==source.read_bytes()
- assert [x['chunk']['index'] for x in remote.calls if x['operation']=='get']==[0,2,3,4]
- def test_short_and_wrong_chunk_never_commit(tmp_path,monkeypatch):
- source,manifest=fixture(tmp_path,monkeypatch);stage=transfer.prepare_stage(tmp_path/'out',manifest)
- chunk=manifest['chunks'][0]
- for content in (b'short',b'x'*chunk['size'],source.read_bytes()[:chunk['size']]+b'extra'):
- with pytest.raises(transfer.TransferError):transfer.receive_part(io.BytesIO(content),stage,chunk)
- assert not transfer.part_path(stage,0).exists()
- def test_wrong_source_hash_and_existing_target_are_preserved(tmp_path,monkeypatch):
- source,manifest=fixture(tmp_path,monkeypatch);dest=tmp_path/'preserve';dest.write_bytes(b'user content')
- with pytest.raises(transfer.TransferError,match='SOURCE_HASH'):
- transfer.download(LocalRemote(),str(source),dest,'0'*64,transfer.MIN_CHUNK)
- with pytest.raises(transfer.TransferError,match='DESTINATION_CONFLICT'):
- transfer.download(LocalRemote(),str(source),dest,manifest['sha256'],transfer.MIN_CHUNK)
- assert dest.read_bytes()==b'user content'
- result=transfer.download(LocalRemote(),str(source),dest,manifest['sha256'],transfer.MIN_CHUNK,True)
- assert result['status']=='PASS' and dest.read_bytes()==source.read_bytes()
- def test_finalized_retry_does_not_transfer_again(tmp_path,monkeypatch):
- source,manifest=fixture(tmp_path,monkeypatch);dest=tmp_path/'out'
- transfer.upload(LocalRemote(),source,str(dest),transfer.MIN_CHUNK)
- remote=LocalRemote();result=transfer.upload(remote,source,str(dest),transfer.MIN_CHUNK)
- assert result['transferred_chunks']==[] and len(remote.calls)==1
- def test_zero_byte_file_and_manifest_boundaries(tmp_path,monkeypatch):
- monkeypatch.setattr(transfer,'REMOTE_ROOT',tmp_path)
- source=tmp_path/'empty';source.touch();dest=tmp_path/'out'
- result=transfer.upload(LocalRemote(),source,str(dest))
- assert result['size']==0 and dest.read_bytes()==b''
- for chunk_bytes in (transfer.MIN_CHUNK-1,transfer.MAX_CHUNK+1):
- with pytest.raises(ValueError):transfer.describe(source,chunk_bytes)
- def test_manifest_gap_and_total_hash_corruption_are_rejected(tmp_path,monkeypatch):
- source,manifest=fixture(tmp_path,monkeypatch)
- manifest['chunks'][0]['offset']=1
- with pytest.raises(ValueError):transfer.validate_manifest(manifest)
- manifest['chunks'][0]['offset']=0;manifest['sha256']='0'*64
- dest=tmp_path/'out'
- with pytest.raises(transfer.TransferError,match='assembled file hash'):
- remote=LocalRemote()
- remote.request({'operation':'prepare','destination':str(dest),'manifest':manifest})
- for chunk in manifest['chunks']:
- remote.request({'operation':'put','destination':str(dest),'sha256':manifest['sha256'],
- 'chunk_bytes':manifest['chunk_bytes'],'index':chunk['index']},source,chunk)
- remote.request({'operation':'finalize','destination':str(dest),'sha256':manifest['sha256'],
- 'chunk_bytes':manifest['chunk_bytes'],'size':manifest['size']})
- assert not dest.exists()
- def test_cleanup_preserves_unexpected_files(tmp_path,monkeypatch):
- source,manifest=fixture(tmp_path,monkeypatch)
- stage=transfer.prepare_stage(tmp_path/'out',manifest);unknown=stage/'keep.txt';unknown.write_text('keep')
- transfer.clean_stage(stage,manifest)
- assert unknown.read_text()=='keep'
- def test_large_manifests_use_stdin_not_command_line(monkeypatch):
- import json
- captured={}
- class Process:
- returncode=0
- def __init__(self,command,**kwargs):captured['command']=command
- def communicate(self,input=None):
- captured['input']=input
- return b'{"complete":false,"missing":[]}',b''
- def poll(self):return 0
- monkeypatch.setattr(transfer.subprocess,'Popen',Process)
- request={'operation':'prepare','manifest':{'chunks':[{'sha256':'a'*64,'index':i} for i in range(2000)]}}
- transfer.SSH('/data/prod2u/source with spaces/remote_transfer.py').request(request)
- assert len(' '.join(captured['command']))<2000
- assert json.loads(captured['input'])==request and len(captured['input'])>32768
- @pytest.mark.parametrize('exit_code',[-1,255,4294967295])
- def test_terminated_ssh_is_reported_as_transport_interruption(monkeypatch,exit_code):
- class Process:
- returncode=exit_code
- def __init__(self,*args,**kwargs):pass
- def communicate(self,input=None):return b'',b''
- def poll(self):return self.returncode
- monkeypatch.setattr(transfer.subprocess,'Popen',Process)
- with pytest.raises(transfer.TransferError) as error:
- transfer.SSH('/data/prod2u/remote_transfer.py',0).request({'operation':'describe'})
- assert error.value.code==255
- def test_cli_reports_unicode_paths_even_when_started_in_cp1252(tmp_path,monkeypatch):
- import json
- monkeypatch.setattr(transfer,'REMOTE_ROOT',tmp_path)
- source=tmp_path/'源.bin';source.write_bytes(b'bytes')
- destination=tmp_path/'目标.bin'
- remote=LocalRemote()
- monkeypatch.setattr(transfer,'SSH',lambda *args:remote)
- output=io.BytesIO();stream=io.TextIOWrapper(output,encoding='cp1252')
- monkeypatch.setattr(transfer.sys,'stdout',stream)
- assert transfer.main(['--remote-worker','fixture','upload',str(source),str(destination)])==0
- stream.flush()
- assert json.loads(output.getvalue().decode('utf-8'))['destination']==str(destination)
|