test_remote_transfer.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import io
  2. from pathlib import Path
  3. import pytest
  4. from tools import remote_transfer as transfer
  5. class LocalRemote:
  6. def __init__(self,fail_operation=None,fail_index=2):
  7. self.fail_operation=fail_operation;self.fail_index=fail_index;self.calls=[]
  8. def request(self,request,source=None,chunk=None,destination=None):
  9. self.calls.append(request.copy())
  10. index=request.get('index',request.get('chunk',{}).get('index'))
  11. if request['operation']==self.fail_operation and index==self.fail_index:
  12. raise transfer.TransferError('injected disconnect',255)
  13. data=io.BytesIO()
  14. if source:
  15. with Path(source).open('rb') as stream:
  16. stream.seek(chunk['offset']);data=io.BytesIO(stream.read(chunk['size']))
  17. output=io.BytesIO()
  18. result=transfer.serve(request,data,output)
  19. if destination:Path(destination).write_bytes(output.getvalue())
  20. return result
  21. def fixture(tmp_path,monkeypatch):
  22. monkeypatch.setattr(transfer,'REMOTE_ROOT',tmp_path)
  23. source=tmp_path/'source with spaces.bin'
  24. source.write_bytes(bytes(range(256))*1024+b'final bytes')
  25. return source,transfer.describe(source,transfer.MIN_CHUNK)
  26. def test_upload_resumes_only_missing_or_corrupt_chunks(tmp_path,monkeypatch):
  27. source,manifest=fixture(tmp_path,monkeypatch);dest=tmp_path/'destination.bin'
  28. broken=LocalRemote('put')
  29. with pytest.raises(transfer.TransferError,match='disconnect'):
  30. transfer.upload(broken,source,str(dest),transfer.MIN_CHUNK)
  31. assert not dest.exists()
  32. stage=transfer.stage_path(dest,manifest['sha256'],transfer.MIN_CHUNK)
  33. transfer.part_path(stage,0).write_bytes(b'corrupt')
  34. remote=LocalRemote();result=transfer.upload(remote,source,str(dest),transfer.MIN_CHUNK)
  35. assert result['transferred_chunks']==[0,2,3,4] and result['reused_chunks']==[1]
  36. assert dest.read_bytes()==source.read_bytes() and not stage.exists()
  37. assert [x['index'] for x in remote.calls if x['operation']=='put']==[0,2,3,4]
  38. def test_download_resumes_only_missing_or_corrupt_chunks(tmp_path,monkeypatch):
  39. source,manifest=fixture(tmp_path,monkeypatch);dest=tmp_path/'download.bin'
  40. with pytest.raises(transfer.TransferError,match='disconnect'):
  41. transfer.download(LocalRemote('get'),str(source),dest,manifest['sha256'],transfer.MIN_CHUNK)
  42. assert not dest.exists()
  43. stage=transfer.stage_path(dest,manifest['sha256'],transfer.MIN_CHUNK)
  44. transfer.part_path(stage,0).write_bytes(b'corrupt')
  45. remote=LocalRemote()
  46. result=transfer.download(remote,str(source),dest,manifest['sha256'],transfer.MIN_CHUNK)
  47. assert result['transferred_chunks']==[0,2,3,4] and result['reused_chunks']==[1]
  48. assert dest.read_bytes()==source.read_bytes()
  49. assert [x['chunk']['index'] for x in remote.calls if x['operation']=='get']==[0,2,3,4]
  50. def test_short_and_wrong_chunk_never_commit(tmp_path,monkeypatch):
  51. source,manifest=fixture(tmp_path,monkeypatch);stage=transfer.prepare_stage(tmp_path/'out',manifest)
  52. chunk=manifest['chunks'][0]
  53. for content in (b'short',b'x'*chunk['size'],source.read_bytes()[:chunk['size']]+b'extra'):
  54. with pytest.raises(transfer.TransferError):transfer.receive_part(io.BytesIO(content),stage,chunk)
  55. assert not transfer.part_path(stage,0).exists()
  56. def test_wrong_source_hash_and_existing_target_are_preserved(tmp_path,monkeypatch):
  57. source,manifest=fixture(tmp_path,monkeypatch);dest=tmp_path/'preserve';dest.write_bytes(b'user content')
  58. with pytest.raises(transfer.TransferError,match='SOURCE_HASH'):
  59. transfer.download(LocalRemote(),str(source),dest,'0'*64,transfer.MIN_CHUNK)
  60. with pytest.raises(transfer.TransferError,match='DESTINATION_CONFLICT'):
  61. transfer.download(LocalRemote(),str(source),dest,manifest['sha256'],transfer.MIN_CHUNK)
  62. assert dest.read_bytes()==b'user content'
  63. result=transfer.download(LocalRemote(),str(source),dest,manifest['sha256'],transfer.MIN_CHUNK,True)
  64. assert result['status']=='PASS' and dest.read_bytes()==source.read_bytes()
  65. def test_finalized_retry_does_not_transfer_again(tmp_path,monkeypatch):
  66. source,manifest=fixture(tmp_path,monkeypatch);dest=tmp_path/'out'
  67. transfer.upload(LocalRemote(),source,str(dest),transfer.MIN_CHUNK)
  68. remote=LocalRemote();result=transfer.upload(remote,source,str(dest),transfer.MIN_CHUNK)
  69. assert result['transferred_chunks']==[] and len(remote.calls)==1
  70. def test_zero_byte_file_and_manifest_boundaries(tmp_path,monkeypatch):
  71. monkeypatch.setattr(transfer,'REMOTE_ROOT',tmp_path)
  72. source=tmp_path/'empty';source.touch();dest=tmp_path/'out'
  73. result=transfer.upload(LocalRemote(),source,str(dest))
  74. assert result['size']==0 and dest.read_bytes()==b''
  75. for chunk_bytes in (transfer.MIN_CHUNK-1,transfer.MAX_CHUNK+1):
  76. with pytest.raises(ValueError):transfer.describe(source,chunk_bytes)
  77. def test_manifest_gap_and_total_hash_corruption_are_rejected(tmp_path,monkeypatch):
  78. source,manifest=fixture(tmp_path,monkeypatch)
  79. manifest['chunks'][0]['offset']=1
  80. with pytest.raises(ValueError):transfer.validate_manifest(manifest)
  81. manifest['chunks'][0]['offset']=0;manifest['sha256']='0'*64
  82. dest=tmp_path/'out'
  83. with pytest.raises(transfer.TransferError,match='assembled file hash'):
  84. remote=LocalRemote()
  85. remote.request({'operation':'prepare','destination':str(dest),'manifest':manifest})
  86. for chunk in manifest['chunks']:
  87. remote.request({'operation':'put','destination':str(dest),'sha256':manifest['sha256'],
  88. 'chunk_bytes':manifest['chunk_bytes'],'index':chunk['index']},source,chunk)
  89. remote.request({'operation':'finalize','destination':str(dest),'sha256':manifest['sha256'],
  90. 'chunk_bytes':manifest['chunk_bytes'],'size':manifest['size']})
  91. assert not dest.exists()
  92. def test_cleanup_preserves_unexpected_files(tmp_path,monkeypatch):
  93. source,manifest=fixture(tmp_path,monkeypatch)
  94. stage=transfer.prepare_stage(tmp_path/'out',manifest);unknown=stage/'keep.txt';unknown.write_text('keep')
  95. transfer.clean_stage(stage,manifest)
  96. assert unknown.read_text()=='keep'
  97. def test_large_manifests_use_stdin_not_command_line(monkeypatch):
  98. import json
  99. captured={}
  100. class Process:
  101. returncode=0
  102. def __init__(self,command,**kwargs):captured['command']=command
  103. def communicate(self,input=None):
  104. captured['input']=input
  105. return b'{"complete":false,"missing":[]}',b''
  106. def poll(self):return 0
  107. monkeypatch.setattr(transfer.subprocess,'Popen',Process)
  108. request={'operation':'prepare','manifest':{'chunks':[{'sha256':'a'*64,'index':i} for i in range(2000)]}}
  109. transfer.SSH('/data/prod2u/source with spaces/remote_transfer.py').request(request)
  110. assert len(' '.join(captured['command']))<2000
  111. assert json.loads(captured['input'])==request and len(captured['input'])>32768
  112. @pytest.mark.parametrize('exit_code',[-1,255,4294967295])
  113. def test_terminated_ssh_is_reported_as_transport_interruption(monkeypatch,exit_code):
  114. class Process:
  115. returncode=exit_code
  116. def __init__(self,*args,**kwargs):pass
  117. def communicate(self,input=None):return b'',b''
  118. def poll(self):return self.returncode
  119. monkeypatch.setattr(transfer.subprocess,'Popen',Process)
  120. with pytest.raises(transfer.TransferError) as error:
  121. transfer.SSH('/data/prod2u/remote_transfer.py',0).request({'operation':'describe'})
  122. assert error.value.code==255
  123. def test_cli_reports_unicode_paths_even_when_started_in_cp1252(tmp_path,monkeypatch):
  124. import json
  125. monkeypatch.setattr(transfer,'REMOTE_ROOT',tmp_path)
  126. source=tmp_path/'源.bin';source.write_bytes(b'bytes')
  127. destination=tmp_path/'目标.bin'
  128. remote=LocalRemote()
  129. monkeypatch.setattr(transfer,'SSH',lambda *args:remote)
  130. output=io.BytesIO();stream=io.TextIOWrapper(output,encoding='cp1252')
  131. monkeypatch.setattr(transfer.sys,'stdout',stream)
  132. assert transfer.main(['--remote-worker','fixture','upload',str(source),str(destination)])==0
  133. stream.flush()
  134. assert json.loads(output.getvalue().decode('utf-8'))['destination']==str(destination)