test_shutil.py 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715
  1. # Copyright (C) 2003 Python Software Foundation
  2. import unittest
  3. import unittest.mock
  4. import shutil
  5. import tempfile
  6. import sys
  7. import stat
  8. import os
  9. import os.path
  10. import errno
  11. import functools
  12. import pathlib
  13. import subprocess
  14. import random
  15. import string
  16. import contextlib
  17. import io
  18. from shutil import (make_archive,
  19. register_archive_format, unregister_archive_format,
  20. get_archive_formats, Error, unpack_archive,
  21. register_unpack_format, RegistryError,
  22. unregister_unpack_format, get_unpack_formats,
  23. SameFileError, _GiveupOnFastCopy)
  24. import tarfile
  25. import zipfile
  26. try:
  27. import posix
  28. except ImportError:
  29. posix = None
  30. from test import support
  31. from test.support import os_helper
  32. from test.support.os_helper import TESTFN, FakePath
  33. TESTFN2 = TESTFN + "2"
  34. TESTFN_SRC = TESTFN + "_SRC"
  35. TESTFN_DST = TESTFN + "_DST"
  36. MACOS = sys.platform.startswith("darwin")
  37. SOLARIS = sys.platform.startswith("sunos")
  38. AIX = sys.platform[:3] == 'aix'
  39. try:
  40. import grp
  41. import pwd
  42. UID_GID_SUPPORT = True
  43. except ImportError:
  44. UID_GID_SUPPORT = False
  45. try:
  46. import _winapi
  47. except ImportError:
  48. _winapi = None
  49. no_chdir = unittest.mock.patch('os.chdir',
  50. side_effect=AssertionError("shouldn't call os.chdir()"))
  51. def _fake_rename(*args, **kwargs):
  52. # Pretend the destination path is on a different filesystem.
  53. raise OSError(getattr(errno, 'EXDEV', 18), "Invalid cross-device link")
  54. def mock_rename(func):
  55. @functools.wraps(func)
  56. def wrap(*args, **kwargs):
  57. try:
  58. builtin_rename = os.rename
  59. os.rename = _fake_rename
  60. return func(*args, **kwargs)
  61. finally:
  62. os.rename = builtin_rename
  63. return wrap
  64. def write_file(path, content, binary=False):
  65. """Write *content* to a file located at *path*.
  66. If *path* is a tuple instead of a string, os.path.join will be used to
  67. make a path. If *binary* is true, the file will be opened in binary
  68. mode.
  69. """
  70. if isinstance(path, tuple):
  71. path = os.path.join(*path)
  72. mode = 'wb' if binary else 'w'
  73. encoding = None if binary else "utf-8"
  74. with open(path, mode, encoding=encoding) as fp:
  75. fp.write(content)
  76. def write_test_file(path, size):
  77. """Create a test file with an arbitrary size and random text content."""
  78. def chunks(total, step):
  79. assert total >= step
  80. while total > step:
  81. yield step
  82. total -= step
  83. if total:
  84. yield total
  85. bufsize = min(size, 8192)
  86. chunk = b"".join([random.choice(string.ascii_letters).encode()
  87. for i in range(bufsize)])
  88. with open(path, 'wb') as f:
  89. for csize in chunks(size, bufsize):
  90. f.write(chunk)
  91. assert os.path.getsize(path) == size
  92. def read_file(path, binary=False):
  93. """Return contents from a file located at *path*.
  94. If *path* is a tuple instead of a string, os.path.join will be used to
  95. make a path. If *binary* is true, the file will be opened in binary
  96. mode.
  97. """
  98. if isinstance(path, tuple):
  99. path = os.path.join(*path)
  100. mode = 'rb' if binary else 'r'
  101. encoding = None if binary else "utf-8"
  102. with open(path, mode, encoding=encoding) as fp:
  103. return fp.read()
  104. def rlistdir(path):
  105. res = []
  106. for name in sorted(os.listdir(path)):
  107. p = os.path.join(path, name)
  108. if os.path.isdir(p) and not os.path.islink(p):
  109. res.append(name + '/')
  110. for n in rlistdir(p):
  111. res.append(name + '/' + n)
  112. else:
  113. res.append(name)
  114. return res
  115. def supports_file2file_sendfile():
  116. # ...apparently Linux and Solaris are the only ones
  117. if not hasattr(os, "sendfile"):
  118. return False
  119. srcname = None
  120. dstname = None
  121. try:
  122. with tempfile.NamedTemporaryFile("wb", dir=os.getcwd(), delete=False) as f:
  123. srcname = f.name
  124. f.write(b"0123456789")
  125. with open(srcname, "rb") as src:
  126. with tempfile.NamedTemporaryFile("wb", dir=os.getcwd(), delete=False) as dst:
  127. dstname = dst.name
  128. infd = src.fileno()
  129. outfd = dst.fileno()
  130. try:
  131. os.sendfile(outfd, infd, 0, 2)
  132. except OSError:
  133. return False
  134. else:
  135. return True
  136. finally:
  137. if srcname is not None:
  138. os_helper.unlink(srcname)
  139. if dstname is not None:
  140. os_helper.unlink(dstname)
  141. SUPPORTS_SENDFILE = supports_file2file_sendfile()
  142. # AIX 32-bit mode, by default, lacks enough memory for the xz/lzma compiler test
  143. # The AIX command 'dump -o program' gives XCOFF header information
  144. # The second word of the last line in the maxdata value
  145. # when 32-bit maxdata must be greater than 0x1000000 for the xz test to succeed
  146. def _maxdataOK():
  147. if AIX and sys.maxsize == 2147483647:
  148. hdrs=subprocess.getoutput("/usr/bin/dump -o %s" % sys.executable)
  149. maxdata=hdrs.split("\n")[-1].split()[1]
  150. return int(maxdata,16) >= 0x20000000
  151. else:
  152. return True
  153. class BaseTest:
  154. def mkdtemp(self, prefix=None):
  155. """Create a temporary directory that will be cleaned up.
  156. Returns the path of the directory.
  157. """
  158. d = tempfile.mkdtemp(prefix=prefix, dir=os.getcwd())
  159. self.addCleanup(os_helper.rmtree, d)
  160. return d
  161. class TestRmTree(BaseTest, unittest.TestCase):
  162. def test_rmtree_works_on_bytes(self):
  163. tmp = self.mkdtemp()
  164. victim = os.path.join(tmp, 'killme')
  165. os.mkdir(victim)
  166. write_file(os.path.join(victim, 'somefile'), 'foo')
  167. victim = os.fsencode(victim)
  168. self.assertIsInstance(victim, bytes)
  169. shutil.rmtree(victim)
  170. @os_helper.skip_unless_symlink
  171. def test_rmtree_fails_on_symlink(self):
  172. tmp = self.mkdtemp()
  173. dir_ = os.path.join(tmp, 'dir')
  174. os.mkdir(dir_)
  175. link = os.path.join(tmp, 'link')
  176. os.symlink(dir_, link)
  177. self.assertRaises(OSError, shutil.rmtree, link)
  178. self.assertTrue(os.path.exists(dir_))
  179. self.assertTrue(os.path.lexists(link))
  180. errors = []
  181. def onerror(*args):
  182. errors.append(args)
  183. shutil.rmtree(link, onerror=onerror)
  184. self.assertEqual(len(errors), 1)
  185. self.assertIs(errors[0][0], os.path.islink)
  186. self.assertEqual(errors[0][1], link)
  187. self.assertIsInstance(errors[0][2][1], OSError)
  188. @os_helper.skip_unless_symlink
  189. def test_rmtree_works_on_symlinks(self):
  190. tmp = self.mkdtemp()
  191. dir1 = os.path.join(tmp, 'dir1')
  192. dir2 = os.path.join(dir1, 'dir2')
  193. dir3 = os.path.join(tmp, 'dir3')
  194. for d in dir1, dir2, dir3:
  195. os.mkdir(d)
  196. file1 = os.path.join(tmp, 'file1')
  197. write_file(file1, 'foo')
  198. link1 = os.path.join(dir1, 'link1')
  199. os.symlink(dir2, link1)
  200. link2 = os.path.join(dir1, 'link2')
  201. os.symlink(dir3, link2)
  202. link3 = os.path.join(dir1, 'link3')
  203. os.symlink(file1, link3)
  204. # make sure symlinks are removed but not followed
  205. shutil.rmtree(dir1)
  206. self.assertFalse(os.path.exists(dir1))
  207. self.assertTrue(os.path.exists(dir3))
  208. self.assertTrue(os.path.exists(file1))
  209. @unittest.skipUnless(_winapi, 'only relevant on Windows')
  210. def test_rmtree_fails_on_junctions(self):
  211. tmp = self.mkdtemp()
  212. dir_ = os.path.join(tmp, 'dir')
  213. os.mkdir(dir_)
  214. link = os.path.join(tmp, 'link')
  215. _winapi.CreateJunction(dir_, link)
  216. self.addCleanup(os_helper.unlink, link)
  217. self.assertRaises(OSError, shutil.rmtree, link)
  218. self.assertTrue(os.path.exists(dir_))
  219. self.assertTrue(os.path.lexists(link))
  220. errors = []
  221. def onerror(*args):
  222. errors.append(args)
  223. shutil.rmtree(link, onerror=onerror)
  224. self.assertEqual(len(errors), 1)
  225. self.assertIs(errors[0][0], os.path.islink)
  226. self.assertEqual(errors[0][1], link)
  227. self.assertIsInstance(errors[0][2][1], OSError)
  228. @unittest.skipUnless(_winapi, 'only relevant on Windows')
  229. def test_rmtree_works_on_junctions(self):
  230. tmp = self.mkdtemp()
  231. dir1 = os.path.join(tmp, 'dir1')
  232. dir2 = os.path.join(dir1, 'dir2')
  233. dir3 = os.path.join(tmp, 'dir3')
  234. for d in dir1, dir2, dir3:
  235. os.mkdir(d)
  236. file1 = os.path.join(tmp, 'file1')
  237. write_file(file1, 'foo')
  238. link1 = os.path.join(dir1, 'link1')
  239. _winapi.CreateJunction(dir2, link1)
  240. link2 = os.path.join(dir1, 'link2')
  241. _winapi.CreateJunction(dir3, link2)
  242. link3 = os.path.join(dir1, 'link3')
  243. _winapi.CreateJunction(file1, link3)
  244. # make sure junctions are removed but not followed
  245. shutil.rmtree(dir1)
  246. self.assertFalse(os.path.exists(dir1))
  247. self.assertTrue(os.path.exists(dir3))
  248. self.assertTrue(os.path.exists(file1))
  249. def test_rmtree_errors(self):
  250. # filename is guaranteed not to exist
  251. filename = tempfile.mktemp(dir=self.mkdtemp())
  252. self.assertRaises(FileNotFoundError, shutil.rmtree, filename)
  253. # test that ignore_errors option is honored
  254. shutil.rmtree(filename, ignore_errors=True)
  255. # existing file
  256. tmpdir = self.mkdtemp()
  257. write_file((tmpdir, "tstfile"), "")
  258. filename = os.path.join(tmpdir, "tstfile")
  259. with self.assertRaises(NotADirectoryError) as cm:
  260. shutil.rmtree(filename)
  261. self.assertEqual(cm.exception.filename, filename)
  262. self.assertTrue(os.path.exists(filename))
  263. # test that ignore_errors option is honored
  264. shutil.rmtree(filename, ignore_errors=True)
  265. self.assertTrue(os.path.exists(filename))
  266. errors = []
  267. def onerror(*args):
  268. errors.append(args)
  269. shutil.rmtree(filename, onerror=onerror)
  270. self.assertEqual(len(errors), 2)
  271. self.assertIs(errors[0][0], os.scandir)
  272. self.assertEqual(errors[0][1], filename)
  273. self.assertIsInstance(errors[0][2][1], NotADirectoryError)
  274. self.assertEqual(errors[0][2][1].filename, filename)
  275. self.assertIs(errors[1][0], os.rmdir)
  276. self.assertEqual(errors[1][1], filename)
  277. self.assertIsInstance(errors[1][2][1], NotADirectoryError)
  278. self.assertEqual(errors[1][2][1].filename, filename)
  279. @unittest.skipIf(sys.platform[:6] == 'cygwin',
  280. "This test can't be run on Cygwin (issue #1071513).")
  281. @os_helper.skip_if_dac_override
  282. @os_helper.skip_unless_working_chmod
  283. def test_on_error(self):
  284. self.errorState = 0
  285. os.mkdir(TESTFN)
  286. self.addCleanup(shutil.rmtree, TESTFN)
  287. self.child_file_path = os.path.join(TESTFN, 'a')
  288. self.child_dir_path = os.path.join(TESTFN, 'b')
  289. os_helper.create_empty_file(self.child_file_path)
  290. os.mkdir(self.child_dir_path)
  291. old_dir_mode = os.stat(TESTFN).st_mode
  292. old_child_file_mode = os.stat(self.child_file_path).st_mode
  293. old_child_dir_mode = os.stat(self.child_dir_path).st_mode
  294. # Make unwritable.
  295. new_mode = stat.S_IREAD|stat.S_IEXEC
  296. os.chmod(self.child_file_path, new_mode)
  297. os.chmod(self.child_dir_path, new_mode)
  298. os.chmod(TESTFN, new_mode)
  299. self.addCleanup(os.chmod, TESTFN, old_dir_mode)
  300. self.addCleanup(os.chmod, self.child_file_path, old_child_file_mode)
  301. self.addCleanup(os.chmod, self.child_dir_path, old_child_dir_mode)
  302. shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
  303. # Test whether onerror has actually been called.
  304. self.assertEqual(self.errorState, 3,
  305. "Expected call to onerror function did not happen.")
  306. def check_args_to_onerror(self, func, arg, exc):
  307. # test_rmtree_errors deliberately runs rmtree
  308. # on a directory that is chmod 500, which will fail.
  309. # This function is run when shutil.rmtree fails.
  310. # 99.9% of the time it initially fails to remove
  311. # a file in the directory, so the first time through
  312. # func is os.remove.
  313. # However, some Linux machines running ZFS on
  314. # FUSE experienced a failure earlier in the process
  315. # at os.listdir. The first failure may legally
  316. # be either.
  317. if self.errorState < 2:
  318. if func is os.unlink:
  319. self.assertEqual(arg, self.child_file_path)
  320. elif func is os.rmdir:
  321. self.assertEqual(arg, self.child_dir_path)
  322. else:
  323. self.assertIs(func, os.listdir)
  324. self.assertIn(arg, [TESTFN, self.child_dir_path])
  325. self.assertTrue(issubclass(exc[0], OSError))
  326. self.errorState += 1
  327. else:
  328. self.assertEqual(func, os.rmdir)
  329. self.assertEqual(arg, TESTFN)
  330. self.assertTrue(issubclass(exc[0], OSError))
  331. self.errorState = 3
  332. def test_rmtree_does_not_choke_on_failing_lstat(self):
  333. try:
  334. orig_lstat = os.lstat
  335. def raiser(fn, *args, **kwargs):
  336. if fn != TESTFN:
  337. raise OSError()
  338. else:
  339. return orig_lstat(fn)
  340. os.lstat = raiser
  341. os.mkdir(TESTFN)
  342. write_file((TESTFN, 'foo'), 'foo')
  343. shutil.rmtree(TESTFN)
  344. finally:
  345. os.lstat = orig_lstat
  346. def test_rmtree_uses_safe_fd_version_if_available(self):
  347. _use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <=
  348. os.supports_dir_fd and
  349. os.listdir in os.supports_fd and
  350. os.stat in os.supports_follow_symlinks)
  351. if _use_fd_functions:
  352. self.assertTrue(shutil._use_fd_functions)
  353. self.assertTrue(shutil.rmtree.avoids_symlink_attacks)
  354. tmp_dir = self.mkdtemp()
  355. d = os.path.join(tmp_dir, 'a')
  356. os.mkdir(d)
  357. try:
  358. real_rmtree = shutil._rmtree_safe_fd
  359. class Called(Exception): pass
  360. def _raiser(*args, **kwargs):
  361. raise Called
  362. shutil._rmtree_safe_fd = _raiser
  363. self.assertRaises(Called, shutil.rmtree, d)
  364. finally:
  365. shutil._rmtree_safe_fd = real_rmtree
  366. else:
  367. self.assertFalse(shutil._use_fd_functions)
  368. self.assertFalse(shutil.rmtree.avoids_symlink_attacks)
  369. @unittest.skipUnless(shutil._use_fd_functions, "dir_fd is not supported")
  370. def test_rmtree_with_dir_fd(self):
  371. tmp_dir = self.mkdtemp()
  372. victim = 'killme'
  373. fullname = os.path.join(tmp_dir, victim)
  374. dir_fd = os.open(tmp_dir, os.O_RDONLY)
  375. self.addCleanup(os.close, dir_fd)
  376. os.mkdir(fullname)
  377. os.mkdir(os.path.join(fullname, 'subdir'))
  378. write_file(os.path.join(fullname, 'subdir', 'somefile'), 'foo')
  379. self.assertTrue(os.path.exists(fullname))
  380. shutil.rmtree(victim, dir_fd=dir_fd)
  381. self.assertFalse(os.path.exists(fullname))
  382. @unittest.skipIf(shutil._use_fd_functions, "dir_fd is supported")
  383. def test_rmtree_with_dir_fd_unsupported(self):
  384. tmp_dir = self.mkdtemp()
  385. with self.assertRaises(NotImplementedError):
  386. shutil.rmtree(tmp_dir, dir_fd=0)
  387. self.assertTrue(os.path.exists(tmp_dir))
  388. def test_rmtree_dont_delete_file(self):
  389. # When called on a file instead of a directory, don't delete it.
  390. handle, path = tempfile.mkstemp(dir=self.mkdtemp())
  391. os.close(handle)
  392. self.assertRaises(NotADirectoryError, shutil.rmtree, path)
  393. os.remove(path)
  394. @os_helper.skip_unless_symlink
  395. def test_rmtree_on_symlink(self):
  396. # bug 1669.
  397. os.mkdir(TESTFN)
  398. try:
  399. src = os.path.join(TESTFN, 'cheese')
  400. dst = os.path.join(TESTFN, 'shop')
  401. os.mkdir(src)
  402. os.symlink(src, dst)
  403. self.assertRaises(OSError, shutil.rmtree, dst)
  404. shutil.rmtree(dst, ignore_errors=True)
  405. finally:
  406. shutil.rmtree(TESTFN, ignore_errors=True)
  407. @unittest.skipUnless(_winapi, 'only relevant on Windows')
  408. def test_rmtree_on_junction(self):
  409. os.mkdir(TESTFN)
  410. try:
  411. src = os.path.join(TESTFN, 'cheese')
  412. dst = os.path.join(TESTFN, 'shop')
  413. os.mkdir(src)
  414. open(os.path.join(src, 'spam'), 'wb').close()
  415. _winapi.CreateJunction(src, dst)
  416. self.assertRaises(OSError, shutil.rmtree, dst)
  417. shutil.rmtree(dst, ignore_errors=True)
  418. finally:
  419. shutil.rmtree(TESTFN, ignore_errors=True)
  420. class TestCopyTree(BaseTest, unittest.TestCase):
  421. def test_copytree_simple(self):
  422. src_dir = self.mkdtemp()
  423. dst_dir = os.path.join(self.mkdtemp(), 'destination')
  424. self.addCleanup(shutil.rmtree, src_dir)
  425. self.addCleanup(shutil.rmtree, os.path.dirname(dst_dir))
  426. write_file((src_dir, 'test.txt'), '123')
  427. os.mkdir(os.path.join(src_dir, 'test_dir'))
  428. write_file((src_dir, 'test_dir', 'test.txt'), '456')
  429. shutil.copytree(src_dir, dst_dir)
  430. self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
  431. self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
  432. self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
  433. 'test.txt')))
  434. actual = read_file((dst_dir, 'test.txt'))
  435. self.assertEqual(actual, '123')
  436. actual = read_file((dst_dir, 'test_dir', 'test.txt'))
  437. self.assertEqual(actual, '456')
  438. def test_copytree_dirs_exist_ok(self):
  439. src_dir = self.mkdtemp()
  440. dst_dir = self.mkdtemp()
  441. self.addCleanup(shutil.rmtree, src_dir)
  442. self.addCleanup(shutil.rmtree, dst_dir)
  443. write_file((src_dir, 'nonexisting.txt'), '123')
  444. os.mkdir(os.path.join(src_dir, 'existing_dir'))
  445. os.mkdir(os.path.join(dst_dir, 'existing_dir'))
  446. write_file((dst_dir, 'existing_dir', 'existing.txt'), 'will be replaced')
  447. write_file((src_dir, 'existing_dir', 'existing.txt'), 'has been replaced')
  448. shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True)
  449. self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'nonexisting.txt')))
  450. self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'existing_dir')))
  451. self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'existing_dir',
  452. 'existing.txt')))
  453. actual = read_file((dst_dir, 'nonexisting.txt'))
  454. self.assertEqual(actual, '123')
  455. actual = read_file((dst_dir, 'existing_dir', 'existing.txt'))
  456. self.assertEqual(actual, 'has been replaced')
  457. with self.assertRaises(FileExistsError):
  458. shutil.copytree(src_dir, dst_dir, dirs_exist_ok=False)
  459. @os_helper.skip_unless_symlink
  460. def test_copytree_symlinks(self):
  461. tmp_dir = self.mkdtemp()
  462. src_dir = os.path.join(tmp_dir, 'src')
  463. dst_dir = os.path.join(tmp_dir, 'dst')
  464. sub_dir = os.path.join(src_dir, 'sub')
  465. os.mkdir(src_dir)
  466. os.mkdir(sub_dir)
  467. write_file((src_dir, 'file.txt'), 'foo')
  468. src_link = os.path.join(sub_dir, 'link')
  469. dst_link = os.path.join(dst_dir, 'sub/link')
  470. os.symlink(os.path.join(src_dir, 'file.txt'),
  471. src_link)
  472. if hasattr(os, 'lchmod'):
  473. os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
  474. if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
  475. os.lchflags(src_link, stat.UF_NODUMP)
  476. src_stat = os.lstat(src_link)
  477. shutil.copytree(src_dir, dst_dir, symlinks=True)
  478. self.assertTrue(os.path.islink(os.path.join(dst_dir, 'sub', 'link')))
  479. actual = os.readlink(os.path.join(dst_dir, 'sub', 'link'))
  480. # Bad practice to blindly strip the prefix as it may be required to
  481. # correctly refer to the file, but we're only comparing paths here.
  482. if os.name == 'nt' and actual.startswith('\\\\?\\'):
  483. actual = actual[4:]
  484. self.assertEqual(actual, os.path.join(src_dir, 'file.txt'))
  485. dst_stat = os.lstat(dst_link)
  486. if hasattr(os, 'lchmod'):
  487. self.assertEqual(dst_stat.st_mode, src_stat.st_mode)
  488. if hasattr(os, 'lchflags'):
  489. self.assertEqual(dst_stat.st_flags, src_stat.st_flags)
  490. def test_copytree_with_exclude(self):
  491. # creating data
  492. join = os.path.join
  493. exists = os.path.exists
  494. src_dir = self.mkdtemp()
  495. try:
  496. dst_dir = join(self.mkdtemp(), 'destination')
  497. write_file((src_dir, 'test.txt'), '123')
  498. write_file((src_dir, 'test.tmp'), '123')
  499. os.mkdir(join(src_dir, 'test_dir'))
  500. write_file((src_dir, 'test_dir', 'test.txt'), '456')
  501. os.mkdir(join(src_dir, 'test_dir2'))
  502. write_file((src_dir, 'test_dir2', 'test.txt'), '456')
  503. os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
  504. os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
  505. write_file((src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
  506. write_file((src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
  507. # testing glob-like patterns
  508. try:
  509. patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
  510. shutil.copytree(src_dir, dst_dir, ignore=patterns)
  511. # checking the result: some elements should not be copied
  512. self.assertTrue(exists(join(dst_dir, 'test.txt')))
  513. self.assertFalse(exists(join(dst_dir, 'test.tmp')))
  514. self.assertFalse(exists(join(dst_dir, 'test_dir2')))
  515. finally:
  516. shutil.rmtree(dst_dir)
  517. try:
  518. patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
  519. shutil.copytree(src_dir, dst_dir, ignore=patterns)
  520. # checking the result: some elements should not be copied
  521. self.assertFalse(exists(join(dst_dir, 'test.tmp')))
  522. self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir2')))
  523. self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir')))
  524. finally:
  525. shutil.rmtree(dst_dir)
  526. # testing callable-style
  527. try:
  528. def _filter(src, names):
  529. res = []
  530. for name in names:
  531. path = os.path.join(src, name)
  532. if (os.path.isdir(path) and
  533. path.split()[-1] == 'subdir'):
  534. res.append(name)
  535. elif os.path.splitext(path)[-1] in ('.py'):
  536. res.append(name)
  537. return res
  538. shutil.copytree(src_dir, dst_dir, ignore=_filter)
  539. # checking the result: some elements should not be copied
  540. self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir2',
  541. 'test.py')))
  542. self.assertFalse(exists(join(dst_dir, 'test_dir2', 'subdir')))
  543. finally:
  544. shutil.rmtree(dst_dir)
  545. finally:
  546. shutil.rmtree(src_dir)
  547. shutil.rmtree(os.path.dirname(dst_dir))
  548. def test_copytree_arg_types_of_ignore(self):
  549. join = os.path.join
  550. exists = os.path.exists
  551. tmp_dir = self.mkdtemp()
  552. src_dir = join(tmp_dir, "source")
  553. os.mkdir(join(src_dir))
  554. os.mkdir(join(src_dir, 'test_dir'))
  555. os.mkdir(os.path.join(src_dir, 'test_dir', 'subdir'))
  556. write_file((src_dir, 'test_dir', 'subdir', 'test.txt'), '456')
  557. invokations = []
  558. def _ignore(src, names):
  559. invokations.append(src)
  560. self.assertIsInstance(src, str)
  561. self.assertIsInstance(names, list)
  562. self.assertEqual(len(names), len(set(names)))
  563. for name in names:
  564. self.assertIsInstance(name, str)
  565. return []
  566. dst_dir = join(self.mkdtemp(), 'destination')
  567. shutil.copytree(src_dir, dst_dir, ignore=_ignore)
  568. self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
  569. 'test.txt')))
  570. dst_dir = join(self.mkdtemp(), 'destination')
  571. shutil.copytree(pathlib.Path(src_dir), dst_dir, ignore=_ignore)
  572. self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
  573. 'test.txt')))
  574. dst_dir = join(self.mkdtemp(), 'destination')
  575. src_dir_entry = list(os.scandir(tmp_dir))[0]
  576. self.assertIsInstance(src_dir_entry, os.DirEntry)
  577. shutil.copytree(src_dir_entry, dst_dir, ignore=_ignore)
  578. self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
  579. 'test.txt')))
  580. self.assertEqual(len(invokations), 9)
  581. def test_copytree_retains_permissions(self):
  582. tmp_dir = self.mkdtemp()
  583. src_dir = os.path.join(tmp_dir, 'source')
  584. os.mkdir(src_dir)
  585. dst_dir = os.path.join(tmp_dir, 'destination')
  586. self.addCleanup(shutil.rmtree, tmp_dir)
  587. os.chmod(src_dir, 0o777)
  588. write_file((src_dir, 'permissive.txt'), '123')
  589. os.chmod(os.path.join(src_dir, 'permissive.txt'), 0o777)
  590. write_file((src_dir, 'restrictive.txt'), '456')
  591. os.chmod(os.path.join(src_dir, 'restrictive.txt'), 0o600)
  592. restrictive_subdir = tempfile.mkdtemp(dir=src_dir)
  593. self.addCleanup(os_helper.rmtree, restrictive_subdir)
  594. os.chmod(restrictive_subdir, 0o600)
  595. shutil.copytree(src_dir, dst_dir)
  596. self.assertEqual(os.stat(src_dir).st_mode, os.stat(dst_dir).st_mode)
  597. self.assertEqual(os.stat(os.path.join(src_dir, 'permissive.txt')).st_mode,
  598. os.stat(os.path.join(dst_dir, 'permissive.txt')).st_mode)
  599. self.assertEqual(os.stat(os.path.join(src_dir, 'restrictive.txt')).st_mode,
  600. os.stat(os.path.join(dst_dir, 'restrictive.txt')).st_mode)
  601. restrictive_subdir_dst = os.path.join(dst_dir,
  602. os.path.split(restrictive_subdir)[1])
  603. self.assertEqual(os.stat(restrictive_subdir).st_mode,
  604. os.stat(restrictive_subdir_dst).st_mode)
  605. @unittest.mock.patch('os.chmod')
  606. def test_copytree_winerror(self, mock_patch):
  607. # When copying to VFAT, copystat() raises OSError. On Windows, the
  608. # exception object has a meaningful 'winerror' attribute, but not
  609. # on other operating systems. Do not assume 'winerror' is set.
  610. src_dir = self.mkdtemp()
  611. dst_dir = os.path.join(self.mkdtemp(), 'destination')
  612. self.addCleanup(shutil.rmtree, src_dir)
  613. self.addCleanup(shutil.rmtree, os.path.dirname(dst_dir))
  614. mock_patch.side_effect = PermissionError('ka-boom')
  615. with self.assertRaises(shutil.Error):
  616. shutil.copytree(src_dir, dst_dir)
  617. def test_copytree_custom_copy_function(self):
  618. # See: https://bugs.python.org/issue35648
  619. def custom_cpfun(a, b):
  620. flag.append(None)
  621. self.assertIsInstance(a, str)
  622. self.assertIsInstance(b, str)
  623. self.assertEqual(a, os.path.join(src, 'foo'))
  624. self.assertEqual(b, os.path.join(dst, 'foo'))
  625. flag = []
  626. src = self.mkdtemp()
  627. dst = tempfile.mktemp(dir=self.mkdtemp())
  628. with open(os.path.join(src, 'foo'), 'w', encoding='utf-8') as f:
  629. f.close()
  630. shutil.copytree(src, dst, copy_function=custom_cpfun)
  631. self.assertEqual(len(flag), 1)
  632. # Issue #3002: copyfile and copytree block indefinitely on named pipes
  633. @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
  634. @os_helper.skip_unless_symlink
  635. @unittest.skipIf(sys.platform == "vxworks",
  636. "fifo requires special path on VxWorks")
  637. def test_copytree_named_pipe(self):
  638. os.mkdir(TESTFN)
  639. try:
  640. subdir = os.path.join(TESTFN, "subdir")
  641. os.mkdir(subdir)
  642. pipe = os.path.join(subdir, "mypipe")
  643. try:
  644. os.mkfifo(pipe)
  645. except PermissionError as e:
  646. self.skipTest('os.mkfifo(): %s' % e)
  647. try:
  648. shutil.copytree(TESTFN, TESTFN2)
  649. except shutil.Error as e:
  650. errors = e.args[0]
  651. self.assertEqual(len(errors), 1)
  652. src, dst, error_msg = errors[0]
  653. self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
  654. else:
  655. self.fail("shutil.Error should have been raised")
  656. finally:
  657. shutil.rmtree(TESTFN, ignore_errors=True)
  658. shutil.rmtree(TESTFN2, ignore_errors=True)
  659. def test_copytree_special_func(self):
  660. src_dir = self.mkdtemp()
  661. dst_dir = os.path.join(self.mkdtemp(), 'destination')
  662. write_file((src_dir, 'test.txt'), '123')
  663. os.mkdir(os.path.join(src_dir, 'test_dir'))
  664. write_file((src_dir, 'test_dir', 'test.txt'), '456')
  665. copied = []
  666. def _copy(src, dst):
  667. copied.append((src, dst))
  668. shutil.copytree(src_dir, dst_dir, copy_function=_copy)
  669. self.assertEqual(len(copied), 2)
  670. @os_helper.skip_unless_symlink
  671. def test_copytree_dangling_symlinks(self):
  672. src_dir = self.mkdtemp()
  673. valid_file = os.path.join(src_dir, 'test.txt')
  674. write_file(valid_file, 'abc')
  675. dir_a = os.path.join(src_dir, 'dir_a')
  676. os.mkdir(dir_a)
  677. for d in src_dir, dir_a:
  678. os.symlink('IDONTEXIST', os.path.join(d, 'broken'))
  679. os.symlink(valid_file, os.path.join(d, 'valid'))
  680. # A dangling symlink should raise an error.
  681. dst_dir = os.path.join(self.mkdtemp(), 'destination')
  682. self.assertRaises(Error, shutil.copytree, src_dir, dst_dir)
  683. # Dangling symlinks should be ignored with the proper flag.
  684. dst_dir = os.path.join(self.mkdtemp(), 'destination2')
  685. shutil.copytree(src_dir, dst_dir, ignore_dangling_symlinks=True)
  686. for root, dirs, files in os.walk(dst_dir):
  687. self.assertNotIn('broken', files)
  688. self.assertIn('valid', files)
  689. # a dangling symlink is copied if symlinks=True
  690. dst_dir = os.path.join(self.mkdtemp(), 'destination3')
  691. shutil.copytree(src_dir, dst_dir, symlinks=True)
  692. self.assertIn('test.txt', os.listdir(dst_dir))
  693. @os_helper.skip_unless_symlink
  694. def test_copytree_symlink_dir(self):
  695. src_dir = self.mkdtemp()
  696. dst_dir = os.path.join(self.mkdtemp(), 'destination')
  697. os.mkdir(os.path.join(src_dir, 'real_dir'))
  698. with open(os.path.join(src_dir, 'real_dir', 'test.txt'), 'wb'):
  699. pass
  700. os.symlink(os.path.join(src_dir, 'real_dir'),
  701. os.path.join(src_dir, 'link_to_dir'),
  702. target_is_directory=True)
  703. shutil.copytree(src_dir, dst_dir, symlinks=False)
  704. self.assertFalse(os.path.islink(os.path.join(dst_dir, 'link_to_dir')))
  705. self.assertIn('test.txt', os.listdir(os.path.join(dst_dir, 'link_to_dir')))
  706. dst_dir = os.path.join(self.mkdtemp(), 'destination2')
  707. shutil.copytree(src_dir, dst_dir, symlinks=True)
  708. self.assertTrue(os.path.islink(os.path.join(dst_dir, 'link_to_dir')))
  709. self.assertIn('test.txt', os.listdir(os.path.join(dst_dir, 'link_to_dir')))
  710. def test_copytree_return_value(self):
  711. # copytree returns its destination path.
  712. src_dir = self.mkdtemp()
  713. dst_dir = src_dir + "dest"
  714. self.addCleanup(shutil.rmtree, dst_dir, True)
  715. src = os.path.join(src_dir, 'foo')
  716. write_file(src, 'foo')
  717. rv = shutil.copytree(src_dir, dst_dir)
  718. self.assertEqual(['foo'], os.listdir(rv))
  719. def test_copytree_subdirectory(self):
  720. # copytree where dst is a subdirectory of src, see Issue 38688
  721. base_dir = self.mkdtemp()
  722. self.addCleanup(shutil.rmtree, base_dir, ignore_errors=True)
  723. src_dir = os.path.join(base_dir, "t", "pg")
  724. dst_dir = os.path.join(src_dir, "somevendor", "1.0")
  725. os.makedirs(src_dir)
  726. src = os.path.join(src_dir, 'pol')
  727. write_file(src, 'pol')
  728. rv = shutil.copytree(src_dir, dst_dir)
  729. self.assertEqual(['pol'], os.listdir(rv))
  730. class TestCopy(BaseTest, unittest.TestCase):
  731. ### shutil.copymode
  732. @os_helper.skip_unless_symlink
  733. def test_copymode_follow_symlinks(self):
  734. tmp_dir = self.mkdtemp()
  735. src = os.path.join(tmp_dir, 'foo')
  736. dst = os.path.join(tmp_dir, 'bar')
  737. src_link = os.path.join(tmp_dir, 'baz')
  738. dst_link = os.path.join(tmp_dir, 'quux')
  739. write_file(src, 'foo')
  740. write_file(dst, 'foo')
  741. os.symlink(src, src_link)
  742. os.symlink(dst, dst_link)
  743. os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
  744. # file to file
  745. os.chmod(dst, stat.S_IRWXO)
  746. self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
  747. shutil.copymode(src, dst)
  748. self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
  749. # On Windows, os.chmod does not follow symlinks (issue #15411)
  750. if os.name != 'nt':
  751. # follow src link
  752. os.chmod(dst, stat.S_IRWXO)
  753. shutil.copymode(src_link, dst)
  754. self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
  755. # follow dst link
  756. os.chmod(dst, stat.S_IRWXO)
  757. shutil.copymode(src, dst_link)
  758. self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
  759. # follow both links
  760. os.chmod(dst, stat.S_IRWXO)
  761. shutil.copymode(src_link, dst_link)
  762. self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
  763. @unittest.skipUnless(hasattr(os, 'lchmod'), 'requires os.lchmod')
  764. @os_helper.skip_unless_symlink
  765. def test_copymode_symlink_to_symlink(self):
  766. tmp_dir = self.mkdtemp()
  767. src = os.path.join(tmp_dir, 'foo')
  768. dst = os.path.join(tmp_dir, 'bar')
  769. src_link = os.path.join(tmp_dir, 'baz')
  770. dst_link = os.path.join(tmp_dir, 'quux')
  771. write_file(src, 'foo')
  772. write_file(dst, 'foo')
  773. os.symlink(src, src_link)
  774. os.symlink(dst, dst_link)
  775. os.chmod(src, stat.S_IRWXU|stat.S_IRWXG)
  776. os.chmod(dst, stat.S_IRWXU)
  777. os.lchmod(src_link, stat.S_IRWXO|stat.S_IRWXG)
  778. # link to link
  779. os.lchmod(dst_link, stat.S_IRWXO)
  780. shutil.copymode(src_link, dst_link, follow_symlinks=False)
  781. self.assertEqual(os.lstat(src_link).st_mode,
  782. os.lstat(dst_link).st_mode)
  783. self.assertNotEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
  784. # src link - use chmod
  785. os.lchmod(dst_link, stat.S_IRWXO)
  786. shutil.copymode(src_link, dst, follow_symlinks=False)
  787. self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
  788. # dst link - use chmod
  789. os.lchmod(dst_link, stat.S_IRWXO)
  790. shutil.copymode(src, dst_link, follow_symlinks=False)
  791. self.assertEqual(os.stat(src).st_mode, os.stat(dst).st_mode)
  792. @unittest.skipIf(hasattr(os, 'lchmod'), 'requires os.lchmod to be missing')
  793. @os_helper.skip_unless_symlink
  794. def test_copymode_symlink_to_symlink_wo_lchmod(self):
  795. tmp_dir = self.mkdtemp()
  796. src = os.path.join(tmp_dir, 'foo')
  797. dst = os.path.join(tmp_dir, 'bar')
  798. src_link = os.path.join(tmp_dir, 'baz')
  799. dst_link = os.path.join(tmp_dir, 'quux')
  800. write_file(src, 'foo')
  801. write_file(dst, 'foo')
  802. os.symlink(src, src_link)
  803. os.symlink(dst, dst_link)
  804. shutil.copymode(src_link, dst_link, follow_symlinks=False) # silent fail
  805. ### shutil.copystat
  806. @os_helper.skip_unless_symlink
  807. def test_copystat_symlinks(self):
  808. tmp_dir = self.mkdtemp()
  809. src = os.path.join(tmp_dir, 'foo')
  810. dst = os.path.join(tmp_dir, 'bar')
  811. src_link = os.path.join(tmp_dir, 'baz')
  812. dst_link = os.path.join(tmp_dir, 'qux')
  813. write_file(src, 'foo')
  814. src_stat = os.stat(src)
  815. os.utime(src, (src_stat.st_atime,
  816. src_stat.st_mtime - 42.0)) # ensure different mtimes
  817. write_file(dst, 'bar')
  818. self.assertNotEqual(os.stat(src).st_mtime, os.stat(dst).st_mtime)
  819. os.symlink(src, src_link)
  820. os.symlink(dst, dst_link)
  821. if hasattr(os, 'lchmod'):
  822. os.lchmod(src_link, stat.S_IRWXO)
  823. if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
  824. os.lchflags(src_link, stat.UF_NODUMP)
  825. src_link_stat = os.lstat(src_link)
  826. # follow
  827. if hasattr(os, 'lchmod'):
  828. shutil.copystat(src_link, dst_link, follow_symlinks=True)
  829. self.assertNotEqual(src_link_stat.st_mode, os.stat(dst).st_mode)
  830. # don't follow
  831. shutil.copystat(src_link, dst_link, follow_symlinks=False)
  832. dst_link_stat = os.lstat(dst_link)
  833. if os.utime in os.supports_follow_symlinks:
  834. for attr in 'st_atime', 'st_mtime':
  835. # The modification times may be truncated in the new file.
  836. self.assertLessEqual(getattr(src_link_stat, attr),
  837. getattr(dst_link_stat, attr) + 1)
  838. if hasattr(os, 'lchmod'):
  839. self.assertEqual(src_link_stat.st_mode, dst_link_stat.st_mode)
  840. if hasattr(os, 'lchflags') and hasattr(src_link_stat, 'st_flags'):
  841. self.assertEqual(src_link_stat.st_flags, dst_link_stat.st_flags)
  842. # tell to follow but dst is not a link
  843. shutil.copystat(src_link, dst, follow_symlinks=False)
  844. self.assertTrue(abs(os.stat(src).st_mtime - os.stat(dst).st_mtime) <
  845. 00000.1)
  846. @unittest.skipUnless(hasattr(os, 'chflags') and
  847. hasattr(errno, 'EOPNOTSUPP') and
  848. hasattr(errno, 'ENOTSUP'),
  849. "requires os.chflags, EOPNOTSUPP & ENOTSUP")
  850. def test_copystat_handles_harmless_chflags_errors(self):
  851. tmpdir = self.mkdtemp()
  852. file1 = os.path.join(tmpdir, 'file1')
  853. file2 = os.path.join(tmpdir, 'file2')
  854. write_file(file1, 'xxx')
  855. write_file(file2, 'xxx')
  856. def make_chflags_raiser(err):
  857. ex = OSError()
  858. def _chflags_raiser(path, flags, *, follow_symlinks=True):
  859. ex.errno = err
  860. raise ex
  861. return _chflags_raiser
  862. old_chflags = os.chflags
  863. try:
  864. for err in errno.EOPNOTSUPP, errno.ENOTSUP:
  865. os.chflags = make_chflags_raiser(err)
  866. shutil.copystat(file1, file2)
  867. # assert others errors break it
  868. os.chflags = make_chflags_raiser(errno.EOPNOTSUPP + errno.ENOTSUP)
  869. self.assertRaises(OSError, shutil.copystat, file1, file2)
  870. finally:
  871. os.chflags = old_chflags
  872. ### shutil.copyxattr
  873. @os_helper.skip_unless_xattr
  874. def test_copyxattr(self):
  875. tmp_dir = self.mkdtemp()
  876. src = os.path.join(tmp_dir, 'foo')
  877. write_file(src, 'foo')
  878. dst = os.path.join(tmp_dir, 'bar')
  879. write_file(dst, 'bar')
  880. # no xattr == no problem
  881. shutil._copyxattr(src, dst)
  882. # common case
  883. os.setxattr(src, 'user.foo', b'42')
  884. os.setxattr(src, 'user.bar', b'43')
  885. shutil._copyxattr(src, dst)
  886. self.assertEqual(sorted(os.listxattr(src)), sorted(os.listxattr(dst)))
  887. self.assertEqual(
  888. os.getxattr(src, 'user.foo'),
  889. os.getxattr(dst, 'user.foo'))
  890. # check errors don't affect other attrs
  891. os.remove(dst)
  892. write_file(dst, 'bar')
  893. os_error = OSError(errno.EPERM, 'EPERM')
  894. def _raise_on_user_foo(fname, attr, val, **kwargs):
  895. if attr == 'user.foo':
  896. raise os_error
  897. else:
  898. orig_setxattr(fname, attr, val, **kwargs)
  899. try:
  900. orig_setxattr = os.setxattr
  901. os.setxattr = _raise_on_user_foo
  902. shutil._copyxattr(src, dst)
  903. self.assertIn('user.bar', os.listxattr(dst))
  904. finally:
  905. os.setxattr = orig_setxattr
  906. # the source filesystem not supporting xattrs should be ok, too.
  907. def _raise_on_src(fname, *, follow_symlinks=True):
  908. if fname == src:
  909. raise OSError(errno.ENOTSUP, 'Operation not supported')
  910. return orig_listxattr(fname, follow_symlinks=follow_symlinks)
  911. try:
  912. orig_listxattr = os.listxattr
  913. os.listxattr = _raise_on_src
  914. shutil._copyxattr(src, dst)
  915. finally:
  916. os.listxattr = orig_listxattr
  917. # test that shutil.copystat copies xattrs
  918. src = os.path.join(tmp_dir, 'the_original')
  919. srcro = os.path.join(tmp_dir, 'the_original_ro')
  920. write_file(src, src)
  921. write_file(srcro, srcro)
  922. os.setxattr(src, 'user.the_value', b'fiddly')
  923. os.setxattr(srcro, 'user.the_value', b'fiddly')
  924. os.chmod(srcro, 0o444)
  925. dst = os.path.join(tmp_dir, 'the_copy')
  926. dstro = os.path.join(tmp_dir, 'the_copy_ro')
  927. write_file(dst, dst)
  928. write_file(dstro, dstro)
  929. shutil.copystat(src, dst)
  930. shutil.copystat(srcro, dstro)
  931. self.assertEqual(os.getxattr(dst, 'user.the_value'), b'fiddly')
  932. self.assertEqual(os.getxattr(dstro, 'user.the_value'), b'fiddly')
  933. @os_helper.skip_unless_symlink
  934. @os_helper.skip_unless_xattr
  935. @os_helper.skip_unless_dac_override
  936. def test_copyxattr_symlinks(self):
  937. # On Linux, it's only possible to access non-user xattr for symlinks;
  938. # which in turn require root privileges. This test should be expanded
  939. # as soon as other platforms gain support for extended attributes.
  940. tmp_dir = self.mkdtemp()
  941. src = os.path.join(tmp_dir, 'foo')
  942. src_link = os.path.join(tmp_dir, 'baz')
  943. write_file(src, 'foo')
  944. os.symlink(src, src_link)
  945. os.setxattr(src, 'trusted.foo', b'42')
  946. os.setxattr(src_link, 'trusted.foo', b'43', follow_symlinks=False)
  947. dst = os.path.join(tmp_dir, 'bar')
  948. dst_link = os.path.join(tmp_dir, 'qux')
  949. write_file(dst, 'bar')
  950. os.symlink(dst, dst_link)
  951. shutil._copyxattr(src_link, dst_link, follow_symlinks=False)
  952. self.assertEqual(os.getxattr(dst_link, 'trusted.foo', follow_symlinks=False), b'43')
  953. self.assertRaises(OSError, os.getxattr, dst, 'trusted.foo')
  954. shutil._copyxattr(src_link, dst, follow_symlinks=False)
  955. self.assertEqual(os.getxattr(dst, 'trusted.foo'), b'43')
  956. ### shutil.copy
  957. def _copy_file(self, method):
  958. fname = 'test.txt'
  959. tmpdir = self.mkdtemp()
  960. write_file((tmpdir, fname), 'xxx')
  961. file1 = os.path.join(tmpdir, fname)
  962. tmpdir2 = self.mkdtemp()
  963. method(file1, tmpdir2)
  964. file2 = os.path.join(tmpdir2, fname)
  965. return (file1, file2)
  966. def test_copy(self):
  967. # Ensure that the copied file exists and has the same mode bits.
  968. file1, file2 = self._copy_file(shutil.copy)
  969. self.assertTrue(os.path.exists(file2))
  970. self.assertEqual(os.stat(file1).st_mode, os.stat(file2).st_mode)
  971. @os_helper.skip_unless_symlink
  972. def test_copy_symlinks(self):
  973. tmp_dir = self.mkdtemp()
  974. src = os.path.join(tmp_dir, 'foo')
  975. dst = os.path.join(tmp_dir, 'bar')
  976. src_link = os.path.join(tmp_dir, 'baz')
  977. write_file(src, 'foo')
  978. os.symlink(src, src_link)
  979. if hasattr(os, 'lchmod'):
  980. os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
  981. # don't follow
  982. shutil.copy(src_link, dst, follow_symlinks=True)
  983. self.assertFalse(os.path.islink(dst))
  984. self.assertEqual(read_file(src), read_file(dst))
  985. os.remove(dst)
  986. # follow
  987. shutil.copy(src_link, dst, follow_symlinks=False)
  988. self.assertTrue(os.path.islink(dst))
  989. self.assertEqual(os.readlink(dst), os.readlink(src_link))
  990. if hasattr(os, 'lchmod'):
  991. self.assertEqual(os.lstat(src_link).st_mode,
  992. os.lstat(dst).st_mode)
  993. ### shutil.copy2
  994. @unittest.skipUnless(hasattr(os, 'utime'), 'requires os.utime')
  995. def test_copy2(self):
  996. # Ensure that the copied file exists and has the same mode and
  997. # modification time bits.
  998. file1, file2 = self._copy_file(shutil.copy2)
  999. self.assertTrue(os.path.exists(file2))
  1000. file1_stat = os.stat(file1)
  1001. file2_stat = os.stat(file2)
  1002. self.assertEqual(file1_stat.st_mode, file2_stat.st_mode)
  1003. for attr in 'st_atime', 'st_mtime':
  1004. # The modification times may be truncated in the new file.
  1005. self.assertLessEqual(getattr(file1_stat, attr),
  1006. getattr(file2_stat, attr) + 1)
  1007. if hasattr(os, 'chflags') and hasattr(file1_stat, 'st_flags'):
  1008. self.assertEqual(getattr(file1_stat, 'st_flags'),
  1009. getattr(file2_stat, 'st_flags'))
  1010. @os_helper.skip_unless_symlink
  1011. def test_copy2_symlinks(self):
  1012. tmp_dir = self.mkdtemp()
  1013. src = os.path.join(tmp_dir, 'foo')
  1014. dst = os.path.join(tmp_dir, 'bar')
  1015. src_link = os.path.join(tmp_dir, 'baz')
  1016. write_file(src, 'foo')
  1017. os.symlink(src, src_link)
  1018. if hasattr(os, 'lchmod'):
  1019. os.lchmod(src_link, stat.S_IRWXU | stat.S_IRWXO)
  1020. if hasattr(os, 'lchflags') and hasattr(stat, 'UF_NODUMP'):
  1021. os.lchflags(src_link, stat.UF_NODUMP)
  1022. src_stat = os.stat(src)
  1023. src_link_stat = os.lstat(src_link)
  1024. # follow
  1025. shutil.copy2(src_link, dst, follow_symlinks=True)
  1026. self.assertFalse(os.path.islink(dst))
  1027. self.assertEqual(read_file(src), read_file(dst))
  1028. os.remove(dst)
  1029. # don't follow
  1030. shutil.copy2(src_link, dst, follow_symlinks=False)
  1031. self.assertTrue(os.path.islink(dst))
  1032. self.assertEqual(os.readlink(dst), os.readlink(src_link))
  1033. dst_stat = os.lstat(dst)
  1034. if os.utime in os.supports_follow_symlinks:
  1035. for attr in 'st_atime', 'st_mtime':
  1036. # The modification times may be truncated in the new file.
  1037. self.assertLessEqual(getattr(src_link_stat, attr),
  1038. getattr(dst_stat, attr) + 1)
  1039. if hasattr(os, 'lchmod'):
  1040. self.assertEqual(src_link_stat.st_mode, dst_stat.st_mode)
  1041. self.assertNotEqual(src_stat.st_mode, dst_stat.st_mode)
  1042. if hasattr(os, 'lchflags') and hasattr(src_link_stat, 'st_flags'):
  1043. self.assertEqual(src_link_stat.st_flags, dst_stat.st_flags)
  1044. @os_helper.skip_unless_xattr
  1045. def test_copy2_xattr(self):
  1046. tmp_dir = self.mkdtemp()
  1047. src = os.path.join(tmp_dir, 'foo')
  1048. dst = os.path.join(tmp_dir, 'bar')
  1049. write_file(src, 'foo')
  1050. os.setxattr(src, 'user.foo', b'42')
  1051. shutil.copy2(src, dst)
  1052. self.assertEqual(
  1053. os.getxattr(src, 'user.foo'),
  1054. os.getxattr(dst, 'user.foo'))
  1055. os.remove(dst)
  1056. def test_copy_return_value(self):
  1057. # copy and copy2 both return their destination path.
  1058. for fn in (shutil.copy, shutil.copy2):
  1059. src_dir = self.mkdtemp()
  1060. dst_dir = self.mkdtemp()
  1061. src = os.path.join(src_dir, 'foo')
  1062. write_file(src, 'foo')
  1063. rv = fn(src, dst_dir)
  1064. self.assertEqual(rv, os.path.join(dst_dir, 'foo'))
  1065. rv = fn(src, os.path.join(dst_dir, 'bar'))
  1066. self.assertEqual(rv, os.path.join(dst_dir, 'bar'))
  1067. def test_copy_dir(self):
  1068. self._test_copy_dir(shutil.copy)
  1069. def test_copy2_dir(self):
  1070. self._test_copy_dir(shutil.copy2)
  1071. def _test_copy_dir(self, copy_func):
  1072. src_dir = self.mkdtemp()
  1073. src_file = os.path.join(src_dir, 'foo')
  1074. dir2 = self.mkdtemp()
  1075. dst = os.path.join(src_dir, 'does_not_exist/')
  1076. write_file(src_file, 'foo')
  1077. if sys.platform == "win32":
  1078. err = PermissionError
  1079. else:
  1080. err = IsADirectoryError
  1081. self.assertRaises(err, copy_func, dir2, src_dir)
  1082. # raise *err* because of src rather than FileNotFoundError because of dst
  1083. self.assertRaises(err, copy_func, dir2, dst)
  1084. copy_func(src_file, dir2) # should not raise exceptions
  1085. ### shutil.copyfile
  1086. @os_helper.skip_unless_symlink
  1087. def test_copyfile_symlinks(self):
  1088. tmp_dir = self.mkdtemp()
  1089. src = os.path.join(tmp_dir, 'src')
  1090. dst = os.path.join(tmp_dir, 'dst')
  1091. dst_link = os.path.join(tmp_dir, 'dst_link')
  1092. link = os.path.join(tmp_dir, 'link')
  1093. write_file(src, 'foo')
  1094. os.symlink(src, link)
  1095. # don't follow
  1096. shutil.copyfile(link, dst_link, follow_symlinks=False)
  1097. self.assertTrue(os.path.islink(dst_link))
  1098. self.assertEqual(os.readlink(link), os.readlink(dst_link))
  1099. # follow
  1100. shutil.copyfile(link, dst)
  1101. self.assertFalse(os.path.islink(dst))
  1102. @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
  1103. def test_dont_copy_file_onto_link_to_itself(self):
  1104. # bug 851123.
  1105. os.mkdir(TESTFN)
  1106. src = os.path.join(TESTFN, 'cheese')
  1107. dst = os.path.join(TESTFN, 'shop')
  1108. try:
  1109. with open(src, 'w', encoding='utf-8') as f:
  1110. f.write('cheddar')
  1111. try:
  1112. os.link(src, dst)
  1113. except PermissionError as e:
  1114. self.skipTest('os.link(): %s' % e)
  1115. self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
  1116. with open(src, 'r', encoding='utf-8') as f:
  1117. self.assertEqual(f.read(), 'cheddar')
  1118. os.remove(dst)
  1119. finally:
  1120. shutil.rmtree(TESTFN, ignore_errors=True)
  1121. @os_helper.skip_unless_symlink
  1122. def test_dont_copy_file_onto_symlink_to_itself(self):
  1123. # bug 851123.
  1124. os.mkdir(TESTFN)
  1125. src = os.path.join(TESTFN, 'cheese')
  1126. dst = os.path.join(TESTFN, 'shop')
  1127. try:
  1128. with open(src, 'w', encoding='utf-8') as f:
  1129. f.write('cheddar')
  1130. # Using `src` here would mean we end up with a symlink pointing
  1131. # to TESTFN/TESTFN/cheese, while it should point at
  1132. # TESTFN/cheese.
  1133. os.symlink('cheese', dst)
  1134. self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
  1135. with open(src, 'r', encoding='utf-8') as f:
  1136. self.assertEqual(f.read(), 'cheddar')
  1137. os.remove(dst)
  1138. finally:
  1139. shutil.rmtree(TESTFN, ignore_errors=True)
  1140. # Issue #3002: copyfile and copytree block indefinitely on named pipes
  1141. @unittest.skipUnless(hasattr(os, "mkfifo"), 'requires os.mkfifo()')
  1142. @unittest.skipIf(sys.platform == "vxworks",
  1143. "fifo requires special path on VxWorks")
  1144. def test_copyfile_named_pipe(self):
  1145. try:
  1146. os.mkfifo(TESTFN)
  1147. except PermissionError as e:
  1148. self.skipTest('os.mkfifo(): %s' % e)
  1149. try:
  1150. self.assertRaises(shutil.SpecialFileError,
  1151. shutil.copyfile, TESTFN, TESTFN2)
  1152. self.assertRaises(shutil.SpecialFileError,
  1153. shutil.copyfile, __file__, TESTFN)
  1154. finally:
  1155. os.remove(TESTFN)
  1156. def test_copyfile_return_value(self):
  1157. # copytree returns its destination path.
  1158. src_dir = self.mkdtemp()
  1159. dst_dir = self.mkdtemp()
  1160. dst_file = os.path.join(dst_dir, 'bar')
  1161. src_file = os.path.join(src_dir, 'foo')
  1162. write_file(src_file, 'foo')
  1163. rv = shutil.copyfile(src_file, dst_file)
  1164. self.assertTrue(os.path.exists(rv))
  1165. self.assertEqual(read_file(src_file), read_file(dst_file))
  1166. def test_copyfile_same_file(self):
  1167. # copyfile() should raise SameFileError if the source and destination
  1168. # are the same.
  1169. src_dir = self.mkdtemp()
  1170. src_file = os.path.join(src_dir, 'foo')
  1171. write_file(src_file, 'foo')
  1172. self.assertRaises(SameFileError, shutil.copyfile, src_file, src_file)
  1173. # But Error should work too, to stay backward compatible.
  1174. self.assertRaises(Error, shutil.copyfile, src_file, src_file)
  1175. # Make sure file is not corrupted.
  1176. self.assertEqual(read_file(src_file), 'foo')
  1177. @unittest.skipIf(MACOS or SOLARIS or _winapi, 'On MACOS, Solaris and Windows the errors are not confusing (though different)')
  1178. # gh-92670: The test uses a trailing slash to force the OS consider
  1179. # the path as a directory, but on AIX the trailing slash has no effect
  1180. # and is considered as a file.
  1181. @unittest.skipIf(AIX, 'Not valid on AIX, see gh-92670')
  1182. def test_copyfile_nonexistent_dir(self):
  1183. # Issue 43219
  1184. src_dir = self.mkdtemp()
  1185. src_file = os.path.join(src_dir, 'foo')
  1186. dst = os.path.join(src_dir, 'does_not_exist/')
  1187. write_file(src_file, 'foo')
  1188. self.assertRaises(FileNotFoundError, shutil.copyfile, src_file, dst)
  1189. def test_copyfile_copy_dir(self):
  1190. # Issue 45234
  1191. # test copy() and copyfile() raising proper exceptions when src and/or
  1192. # dst are directories
  1193. src_dir = self.mkdtemp()
  1194. src_file = os.path.join(src_dir, 'foo')
  1195. dir2 = self.mkdtemp()
  1196. dst = os.path.join(src_dir, 'does_not_exist/')
  1197. write_file(src_file, 'foo')
  1198. if sys.platform == "win32":
  1199. err = PermissionError
  1200. else:
  1201. err = IsADirectoryError
  1202. self.assertRaises(err, shutil.copyfile, src_dir, dst)
  1203. self.assertRaises(err, shutil.copyfile, src_file, src_dir)
  1204. self.assertRaises(err, shutil.copyfile, dir2, src_dir)
  1205. class TestArchives(BaseTest, unittest.TestCase):
  1206. ### shutil.make_archive
  1207. @support.requires_zlib()
  1208. def test_make_tarball(self):
  1209. # creating something to tar
  1210. root_dir, base_dir = self._create_files('')
  1211. tmpdir2 = self.mkdtemp()
  1212. # force shutil to create the directory
  1213. os.rmdir(tmpdir2)
  1214. # working with relative paths
  1215. work_dir = os.path.dirname(tmpdir2)
  1216. rel_base_name = os.path.join(os.path.basename(tmpdir2), 'archive')
  1217. with os_helper.change_cwd(work_dir), no_chdir:
  1218. base_name = os.path.abspath(rel_base_name)
  1219. tarball = make_archive(rel_base_name, 'gztar', root_dir, '.')
  1220. # check if the compressed tarball was created
  1221. self.assertEqual(tarball, base_name + '.tar.gz')
  1222. self.assertTrue(os.path.isfile(tarball))
  1223. self.assertTrue(tarfile.is_tarfile(tarball))
  1224. with tarfile.open(tarball, 'r:gz') as tf:
  1225. self.assertCountEqual(tf.getnames(),
  1226. ['.', './sub', './sub2',
  1227. './file1', './file2', './sub/file3'])
  1228. # trying an uncompressed one
  1229. with os_helper.change_cwd(work_dir), no_chdir:
  1230. tarball = make_archive(rel_base_name, 'tar', root_dir, '.')
  1231. self.assertEqual(tarball, base_name + '.tar')
  1232. self.assertTrue(os.path.isfile(tarball))
  1233. self.assertTrue(tarfile.is_tarfile(tarball))
  1234. with tarfile.open(tarball, 'r') as tf:
  1235. self.assertCountEqual(tf.getnames(),
  1236. ['.', './sub', './sub2',
  1237. './file1', './file2', './sub/file3'])
  1238. def _tarinfo(self, path):
  1239. with tarfile.open(path) as tar:
  1240. names = tar.getnames()
  1241. names.sort()
  1242. return tuple(names)
  1243. def _create_files(self, base_dir='dist'):
  1244. # creating something to tar
  1245. root_dir = self.mkdtemp()
  1246. dist = os.path.join(root_dir, base_dir)
  1247. os.makedirs(dist, exist_ok=True)
  1248. write_file((dist, 'file1'), 'xxx')
  1249. write_file((dist, 'file2'), 'xxx')
  1250. os.mkdir(os.path.join(dist, 'sub'))
  1251. write_file((dist, 'sub', 'file3'), 'xxx')
  1252. os.mkdir(os.path.join(dist, 'sub2'))
  1253. if base_dir:
  1254. write_file((root_dir, 'outer'), 'xxx')
  1255. return root_dir, base_dir
  1256. @support.requires_zlib()
  1257. @unittest.skipUnless(shutil.which('tar'),
  1258. 'Need the tar command to run')
  1259. def test_tarfile_vs_tar(self):
  1260. root_dir, base_dir = self._create_files()
  1261. base_name = os.path.join(self.mkdtemp(), 'archive')
  1262. with no_chdir:
  1263. tarball = make_archive(base_name, 'gztar', root_dir, base_dir)
  1264. # check if the compressed tarball was created
  1265. self.assertEqual(tarball, base_name + '.tar.gz')
  1266. self.assertTrue(os.path.isfile(tarball))
  1267. # now create another tarball using `tar`
  1268. tarball2 = os.path.join(root_dir, 'archive2.tar')
  1269. tar_cmd = ['tar', '-cf', 'archive2.tar', base_dir]
  1270. subprocess.check_call(tar_cmd, cwd=root_dir,
  1271. stdout=subprocess.DEVNULL)
  1272. self.assertTrue(os.path.isfile(tarball2))
  1273. # let's compare both tarballs
  1274. self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
  1275. # trying an uncompressed one
  1276. with no_chdir:
  1277. tarball = make_archive(base_name, 'tar', root_dir, base_dir)
  1278. self.assertEqual(tarball, base_name + '.tar')
  1279. self.assertTrue(os.path.isfile(tarball))
  1280. # now for a dry_run
  1281. with no_chdir:
  1282. tarball = make_archive(base_name, 'tar', root_dir, base_dir,
  1283. dry_run=True)
  1284. self.assertEqual(tarball, base_name + '.tar')
  1285. self.assertTrue(os.path.isfile(tarball))
  1286. @support.requires_zlib()
  1287. def test_make_zipfile(self):
  1288. # creating something to zip
  1289. root_dir, base_dir = self._create_files()
  1290. tmpdir2 = self.mkdtemp()
  1291. # force shutil to create the directory
  1292. os.rmdir(tmpdir2)
  1293. # working with relative paths
  1294. work_dir = os.path.dirname(tmpdir2)
  1295. rel_base_name = os.path.join(os.path.basename(tmpdir2), 'archive')
  1296. with os_helper.change_cwd(work_dir), no_chdir:
  1297. base_name = os.path.abspath(rel_base_name)
  1298. res = make_archive(rel_base_name, 'zip', root_dir)
  1299. self.assertEqual(res, base_name + '.zip')
  1300. self.assertTrue(os.path.isfile(res))
  1301. self.assertTrue(zipfile.is_zipfile(res))
  1302. with zipfile.ZipFile(res) as zf:
  1303. self.assertCountEqual(zf.namelist(),
  1304. ['dist/', 'dist/sub/', 'dist/sub2/',
  1305. 'dist/file1', 'dist/file2', 'dist/sub/file3',
  1306. 'outer'])
  1307. with os_helper.change_cwd(work_dir), no_chdir:
  1308. base_name = os.path.abspath(rel_base_name)
  1309. res = make_archive(rel_base_name, 'zip', root_dir, base_dir)
  1310. self.assertEqual(res, base_name + '.zip')
  1311. self.assertTrue(os.path.isfile(res))
  1312. self.assertTrue(zipfile.is_zipfile(res))
  1313. with zipfile.ZipFile(res) as zf:
  1314. self.assertCountEqual(zf.namelist(),
  1315. ['dist/', 'dist/sub/', 'dist/sub2/',
  1316. 'dist/file1', 'dist/file2', 'dist/sub/file3'])
  1317. @support.requires_zlib()
  1318. @unittest.skipUnless(shutil.which('zip'),
  1319. 'Need the zip command to run')
  1320. def test_zipfile_vs_zip(self):
  1321. root_dir, base_dir = self._create_files()
  1322. base_name = os.path.join(self.mkdtemp(), 'archive')
  1323. with no_chdir:
  1324. archive = make_archive(base_name, 'zip', root_dir, base_dir)
  1325. # check if ZIP file was created
  1326. self.assertEqual(archive, base_name + '.zip')
  1327. self.assertTrue(os.path.isfile(archive))
  1328. # now create another ZIP file using `zip`
  1329. archive2 = os.path.join(root_dir, 'archive2.zip')
  1330. zip_cmd = ['zip', '-q', '-r', 'archive2.zip', base_dir]
  1331. subprocess.check_call(zip_cmd, cwd=root_dir,
  1332. stdout=subprocess.DEVNULL)
  1333. self.assertTrue(os.path.isfile(archive2))
  1334. # let's compare both ZIP files
  1335. with zipfile.ZipFile(archive) as zf:
  1336. names = zf.namelist()
  1337. with zipfile.ZipFile(archive2) as zf:
  1338. names2 = zf.namelist()
  1339. self.assertEqual(sorted(names), sorted(names2))
  1340. @support.requires_zlib()
  1341. @unittest.skipUnless(shutil.which('unzip'),
  1342. 'Need the unzip command to run')
  1343. def test_unzip_zipfile(self):
  1344. root_dir, base_dir = self._create_files()
  1345. base_name = os.path.join(self.mkdtemp(), 'archive')
  1346. with no_chdir:
  1347. archive = make_archive(base_name, 'zip', root_dir, base_dir)
  1348. # check if ZIP file was created
  1349. self.assertEqual(archive, base_name + '.zip')
  1350. self.assertTrue(os.path.isfile(archive))
  1351. # now check the ZIP file using `unzip -t`
  1352. zip_cmd = ['unzip', '-t', archive]
  1353. with os_helper.change_cwd(root_dir):
  1354. try:
  1355. subprocess.check_output(zip_cmd, stderr=subprocess.STDOUT)
  1356. except subprocess.CalledProcessError as exc:
  1357. details = exc.output.decode(errors="replace")
  1358. if 'unrecognized option: t' in details:
  1359. self.skipTest("unzip doesn't support -t")
  1360. msg = "{}\n\n**Unzip Output**\n{}"
  1361. self.fail(msg.format(exc, details))
  1362. def test_make_archive(self):
  1363. tmpdir = self.mkdtemp()
  1364. base_name = os.path.join(tmpdir, 'archive')
  1365. self.assertRaises(ValueError, make_archive, base_name, 'xxx')
  1366. @support.requires_zlib()
  1367. def test_make_archive_owner_group(self):
  1368. # testing make_archive with owner and group, with various combinations
  1369. # this works even if there's not gid/uid support
  1370. if UID_GID_SUPPORT:
  1371. group = grp.getgrgid(0)[0]
  1372. owner = pwd.getpwuid(0)[0]
  1373. else:
  1374. group = owner = 'root'
  1375. root_dir, base_dir = self._create_files()
  1376. base_name = os.path.join(self.mkdtemp(), 'archive')
  1377. res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
  1378. group=group)
  1379. self.assertTrue(os.path.isfile(res))
  1380. res = make_archive(base_name, 'zip', root_dir, base_dir)
  1381. self.assertTrue(os.path.isfile(res))
  1382. res = make_archive(base_name, 'tar', root_dir, base_dir,
  1383. owner=owner, group=group)
  1384. self.assertTrue(os.path.isfile(res))
  1385. res = make_archive(base_name, 'tar', root_dir, base_dir,
  1386. owner='kjhkjhkjg', group='oihohoh')
  1387. self.assertTrue(os.path.isfile(res))
  1388. @support.requires_zlib()
  1389. @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
  1390. def test_tarfile_root_owner(self):
  1391. root_dir, base_dir = self._create_files()
  1392. base_name = os.path.join(self.mkdtemp(), 'archive')
  1393. group = grp.getgrgid(0)[0]
  1394. owner = pwd.getpwuid(0)[0]
  1395. with os_helper.change_cwd(root_dir), no_chdir:
  1396. archive_name = make_archive(base_name, 'gztar', root_dir, 'dist',
  1397. owner=owner, group=group)
  1398. # check if the compressed tarball was created
  1399. self.assertTrue(os.path.isfile(archive_name))
  1400. # now checks the rights
  1401. archive = tarfile.open(archive_name)
  1402. try:
  1403. for member in archive.getmembers():
  1404. self.assertEqual(member.uid, 0)
  1405. self.assertEqual(member.gid, 0)
  1406. finally:
  1407. archive.close()
  1408. def test_make_archive_cwd(self):
  1409. current_dir = os.getcwd()
  1410. root_dir = self.mkdtemp()
  1411. def _breaks(*args, **kw):
  1412. raise RuntimeError()
  1413. dirs = []
  1414. def _chdir(path):
  1415. dirs.append(path)
  1416. orig_chdir(path)
  1417. register_archive_format('xxx', _breaks, [], 'xxx file')
  1418. try:
  1419. with support.swap_attr(os, 'chdir', _chdir) as orig_chdir:
  1420. try:
  1421. make_archive('xxx', 'xxx', root_dir=root_dir)
  1422. except Exception:
  1423. pass
  1424. self.assertEqual(os.getcwd(), current_dir)
  1425. self.assertEqual(dirs, [root_dir, current_dir])
  1426. finally:
  1427. unregister_archive_format('xxx')
  1428. def test_make_tarfile_in_curdir(self):
  1429. # Issue #21280
  1430. root_dir = self.mkdtemp()
  1431. with os_helper.change_cwd(root_dir), no_chdir:
  1432. self.assertEqual(make_archive('test', 'tar'), 'test.tar')
  1433. self.assertTrue(os.path.isfile('test.tar'))
  1434. @support.requires_zlib()
  1435. def test_make_zipfile_in_curdir(self):
  1436. # Issue #21280
  1437. root_dir = self.mkdtemp()
  1438. with os_helper.change_cwd(root_dir), no_chdir:
  1439. self.assertEqual(make_archive('test', 'zip'), 'test.zip')
  1440. self.assertTrue(os.path.isfile('test.zip'))
  1441. def test_register_archive_format(self):
  1442. self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
  1443. self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
  1444. 1)
  1445. self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
  1446. [(1, 2), (1, 2, 3)])
  1447. register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
  1448. formats = [name for name, params in get_archive_formats()]
  1449. self.assertIn('xxx', formats)
  1450. unregister_archive_format('xxx')
  1451. formats = [name for name, params in get_archive_formats()]
  1452. self.assertNotIn('xxx', formats)
  1453. ### shutil.unpack_archive
  1454. def check_unpack_archive(self, format):
  1455. self.check_unpack_archive_with_converter(format, lambda path: path)
  1456. self.check_unpack_archive_with_converter(format, pathlib.Path)
  1457. self.check_unpack_archive_with_converter(format, FakePath)
  1458. def check_unpack_archive_with_converter(self, format, converter):
  1459. root_dir, base_dir = self._create_files()
  1460. expected = rlistdir(root_dir)
  1461. expected.remove('outer')
  1462. base_name = os.path.join(self.mkdtemp(), 'archive')
  1463. filename = make_archive(base_name, format, root_dir, base_dir)
  1464. # let's try to unpack it now
  1465. tmpdir2 = self.mkdtemp()
  1466. unpack_archive(converter(filename), converter(tmpdir2))
  1467. self.assertEqual(rlistdir(tmpdir2), expected)
  1468. # and again, this time with the format specified
  1469. tmpdir3 = self.mkdtemp()
  1470. unpack_archive(converter(filename), converter(tmpdir3), format=format)
  1471. self.assertEqual(rlistdir(tmpdir3), expected)
  1472. self.assertRaises(shutil.ReadError, unpack_archive, converter(TESTFN))
  1473. self.assertRaises(ValueError, unpack_archive, converter(TESTFN), format='xxx')
  1474. def test_unpack_archive_tar(self):
  1475. self.check_unpack_archive('tar')
  1476. @support.requires_zlib()
  1477. def test_unpack_archive_gztar(self):
  1478. self.check_unpack_archive('gztar')
  1479. @support.requires_bz2()
  1480. def test_unpack_archive_bztar(self):
  1481. self.check_unpack_archive('bztar')
  1482. @support.requires_lzma()
  1483. @unittest.skipIf(AIX and not _maxdataOK(), "AIX MAXDATA must be 0x20000000 or larger")
  1484. def test_unpack_archive_xztar(self):
  1485. self.check_unpack_archive('xztar')
  1486. @support.requires_zlib()
  1487. def test_unpack_archive_zip(self):
  1488. self.check_unpack_archive('zip')
  1489. def test_unpack_registry(self):
  1490. formats = get_unpack_formats()
  1491. def _boo(filename, extract_dir, extra):
  1492. self.assertEqual(extra, 1)
  1493. self.assertEqual(filename, 'stuff.boo')
  1494. self.assertEqual(extract_dir, 'xx')
  1495. register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
  1496. unpack_archive('stuff.boo', 'xx')
  1497. # trying to register a .boo unpacker again
  1498. self.assertRaises(RegistryError, register_unpack_format, 'Boo2',
  1499. ['.boo'], _boo)
  1500. # should work now
  1501. unregister_unpack_format('Boo')
  1502. register_unpack_format('Boo2', ['.boo'], _boo)
  1503. self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats())
  1504. self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats())
  1505. # let's leave a clean state
  1506. unregister_unpack_format('Boo2')
  1507. self.assertEqual(get_unpack_formats(), formats)
  1508. class TestMisc(BaseTest, unittest.TestCase):
  1509. @unittest.skipUnless(hasattr(shutil, 'disk_usage'),
  1510. "disk_usage not available on this platform")
  1511. def test_disk_usage(self):
  1512. usage = shutil.disk_usage(os.path.dirname(__file__))
  1513. for attr in ('total', 'used', 'free'):
  1514. self.assertIsInstance(getattr(usage, attr), int)
  1515. self.assertGreater(usage.total, 0)
  1516. self.assertGreater(usage.used, 0)
  1517. self.assertGreaterEqual(usage.free, 0)
  1518. self.assertGreaterEqual(usage.total, usage.used)
  1519. self.assertGreater(usage.total, usage.free)
  1520. # bpo-32557: Check that disk_usage() also accepts a filename
  1521. shutil.disk_usage(__file__)
  1522. @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
  1523. @unittest.skipUnless(hasattr(os, 'chown'), 'requires os.chown')
  1524. def test_chown(self):
  1525. dirname = self.mkdtemp()
  1526. filename = tempfile.mktemp(dir=dirname)
  1527. write_file(filename, 'testing chown function')
  1528. with self.assertRaises(ValueError):
  1529. shutil.chown(filename)
  1530. with self.assertRaises(LookupError):
  1531. shutil.chown(filename, user='non-existing username')
  1532. with self.assertRaises(LookupError):
  1533. shutil.chown(filename, group='non-existing groupname')
  1534. with self.assertRaises(TypeError):
  1535. shutil.chown(filename, b'spam')
  1536. with self.assertRaises(TypeError):
  1537. shutil.chown(filename, 3.14)
  1538. uid = os.getuid()
  1539. gid = os.getgid()
  1540. def check_chown(path, uid=None, gid=None):
  1541. s = os.stat(filename)
  1542. if uid is not None:
  1543. self.assertEqual(uid, s.st_uid)
  1544. if gid is not None:
  1545. self.assertEqual(gid, s.st_gid)
  1546. shutil.chown(filename, uid, gid)
  1547. check_chown(filename, uid, gid)
  1548. shutil.chown(filename, uid)
  1549. check_chown(filename, uid)
  1550. shutil.chown(filename, user=uid)
  1551. check_chown(filename, uid)
  1552. shutil.chown(filename, group=gid)
  1553. check_chown(filename, gid=gid)
  1554. shutil.chown(dirname, uid, gid)
  1555. check_chown(dirname, uid, gid)
  1556. shutil.chown(dirname, uid)
  1557. check_chown(dirname, uid)
  1558. shutil.chown(dirname, user=uid)
  1559. check_chown(dirname, uid)
  1560. shutil.chown(dirname, group=gid)
  1561. check_chown(dirname, gid=gid)
  1562. try:
  1563. user = pwd.getpwuid(uid)[0]
  1564. group = grp.getgrgid(gid)[0]
  1565. except KeyError:
  1566. # On some systems uid/gid cannot be resolved.
  1567. pass
  1568. else:
  1569. shutil.chown(filename, user, group)
  1570. check_chown(filename, uid, gid)
  1571. shutil.chown(dirname, user, group)
  1572. check_chown(dirname, uid, gid)
  1573. class TestWhich(BaseTest, unittest.TestCase):
  1574. def setUp(self):
  1575. self.temp_dir = self.mkdtemp(prefix="Tmp")
  1576. # Give the temp_file an ".exe" suffix for all.
  1577. # It's needed on Windows and not harmful on other platforms.
  1578. self.temp_file = tempfile.NamedTemporaryFile(dir=self.temp_dir,
  1579. prefix="Tmp",
  1580. suffix=".Exe")
  1581. os.chmod(self.temp_file.name, stat.S_IXUSR)
  1582. self.addCleanup(self.temp_file.close)
  1583. self.dir, self.file = os.path.split(self.temp_file.name)
  1584. self.env_path = self.dir
  1585. self.curdir = os.curdir
  1586. self.ext = ".EXE"
  1587. def test_basic(self):
  1588. # Given an EXE in a directory, it should be returned.
  1589. rv = shutil.which(self.file, path=self.dir)
  1590. self.assertEqual(rv, self.temp_file.name)
  1591. def test_absolute_cmd(self):
  1592. # When given the fully qualified path to an executable that exists,
  1593. # it should be returned.
  1594. rv = shutil.which(self.temp_file.name, path=self.temp_dir)
  1595. self.assertEqual(rv, self.temp_file.name)
  1596. def test_relative_cmd(self):
  1597. # When given the relative path with a directory part to an executable
  1598. # that exists, it should be returned.
  1599. base_dir, tail_dir = os.path.split(self.dir)
  1600. relpath = os.path.join(tail_dir, self.file)
  1601. with os_helper.change_cwd(path=base_dir):
  1602. rv = shutil.which(relpath, path=self.temp_dir)
  1603. self.assertEqual(rv, relpath)
  1604. # But it shouldn't be searched in PATH directories (issue #16957).
  1605. with os_helper.change_cwd(path=self.dir):
  1606. rv = shutil.which(relpath, path=base_dir)
  1607. self.assertIsNone(rv)
  1608. def test_cwd(self):
  1609. # Issue #16957
  1610. base_dir = os.path.dirname(self.dir)
  1611. with os_helper.change_cwd(path=self.dir):
  1612. rv = shutil.which(self.file, path=base_dir)
  1613. if sys.platform == "win32":
  1614. # Windows: current directory implicitly on PATH
  1615. self.assertEqual(rv, os.path.join(self.curdir, self.file))
  1616. else:
  1617. # Other platforms: shouldn't match in the current directory.
  1618. self.assertIsNone(rv)
  1619. @os_helper.skip_if_dac_override
  1620. def test_non_matching_mode(self):
  1621. # Set the file read-only and ask for writeable files.
  1622. os.chmod(self.temp_file.name, stat.S_IREAD)
  1623. if os.access(self.temp_file.name, os.W_OK):
  1624. self.skipTest("can't set the file read-only")
  1625. rv = shutil.which(self.file, path=self.dir, mode=os.W_OK)
  1626. self.assertIsNone(rv)
  1627. def test_relative_path(self):
  1628. base_dir, tail_dir = os.path.split(self.dir)
  1629. with os_helper.change_cwd(path=base_dir):
  1630. rv = shutil.which(self.file, path=tail_dir)
  1631. self.assertEqual(rv, os.path.join(tail_dir, self.file))
  1632. def test_nonexistent_file(self):
  1633. # Return None when no matching executable file is found on the path.
  1634. rv = shutil.which("foo.exe", path=self.dir)
  1635. self.assertIsNone(rv)
  1636. @unittest.skipUnless(sys.platform == "win32",
  1637. "pathext check is Windows-only")
  1638. def test_pathext_checking(self):
  1639. # Ask for the file without the ".exe" extension, then ensure that
  1640. # it gets found properly with the extension.
  1641. rv = shutil.which(self.file[:-4], path=self.dir)
  1642. self.assertEqual(rv, self.temp_file.name[:-4] + self.ext)
  1643. def test_environ_path(self):
  1644. with os_helper.EnvironmentVarGuard() as env:
  1645. env['PATH'] = self.env_path
  1646. rv = shutil.which(self.file)
  1647. self.assertEqual(rv, self.temp_file.name)
  1648. def test_environ_path_empty(self):
  1649. # PATH='': no match
  1650. with os_helper.EnvironmentVarGuard() as env:
  1651. env['PATH'] = ''
  1652. with unittest.mock.patch('os.confstr', return_value=self.dir, \
  1653. create=True), \
  1654. support.swap_attr(os, 'defpath', self.dir), \
  1655. os_helper.change_cwd(self.dir):
  1656. rv = shutil.which(self.file)
  1657. self.assertIsNone(rv)
  1658. def test_environ_path_cwd(self):
  1659. expected_cwd = os.path.basename(self.temp_file.name)
  1660. if sys.platform == "win32":
  1661. curdir = os.curdir
  1662. if isinstance(expected_cwd, bytes):
  1663. curdir = os.fsencode(curdir)
  1664. expected_cwd = os.path.join(curdir, expected_cwd)
  1665. # PATH=':': explicitly looks in the current directory
  1666. with os_helper.EnvironmentVarGuard() as env:
  1667. env['PATH'] = os.pathsep
  1668. with unittest.mock.patch('os.confstr', return_value=self.dir, \
  1669. create=True), \
  1670. support.swap_attr(os, 'defpath', self.dir):
  1671. rv = shutil.which(self.file)
  1672. self.assertIsNone(rv)
  1673. # look in current directory
  1674. with os_helper.change_cwd(self.dir):
  1675. rv = shutil.which(self.file)
  1676. self.assertEqual(rv, expected_cwd)
  1677. def test_environ_path_missing(self):
  1678. with os_helper.EnvironmentVarGuard() as env:
  1679. env.pop('PATH', None)
  1680. # without confstr
  1681. with unittest.mock.patch('os.confstr', side_effect=ValueError, \
  1682. create=True), \
  1683. support.swap_attr(os, 'defpath', self.dir):
  1684. rv = shutil.which(self.file)
  1685. self.assertEqual(rv, self.temp_file.name)
  1686. # with confstr
  1687. with unittest.mock.patch('os.confstr', return_value=self.dir, \
  1688. create=True), \
  1689. support.swap_attr(os, 'defpath', ''):
  1690. rv = shutil.which(self.file)
  1691. self.assertEqual(rv, self.temp_file.name)
  1692. def test_empty_path(self):
  1693. base_dir = os.path.dirname(self.dir)
  1694. with os_helper.change_cwd(path=self.dir), \
  1695. os_helper.EnvironmentVarGuard() as env:
  1696. env['PATH'] = self.env_path
  1697. rv = shutil.which(self.file, path='')
  1698. self.assertIsNone(rv)
  1699. def test_empty_path_no_PATH(self):
  1700. with os_helper.EnvironmentVarGuard() as env:
  1701. env.pop('PATH', None)
  1702. rv = shutil.which(self.file)
  1703. self.assertIsNone(rv)
  1704. @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
  1705. def test_pathext(self):
  1706. ext = ".xyz"
  1707. temp_filexyz = tempfile.NamedTemporaryFile(dir=self.temp_dir,
  1708. prefix="Tmp2", suffix=ext)
  1709. os.chmod(temp_filexyz.name, stat.S_IXUSR)
  1710. self.addCleanup(temp_filexyz.close)
  1711. # strip path and extension
  1712. program = os.path.basename(temp_filexyz.name)
  1713. program = os.path.splitext(program)[0]
  1714. with os_helper.EnvironmentVarGuard() as env:
  1715. env['PATHEXT'] = ext
  1716. rv = shutil.which(program, path=self.temp_dir)
  1717. self.assertEqual(rv, temp_filexyz.name)
  1718. # Issue 40592: See https://bugs.python.org/issue40592
  1719. @unittest.skipUnless(sys.platform == "win32", 'test specific to Windows')
  1720. def test_pathext_with_empty_str(self):
  1721. ext = ".xyz"
  1722. temp_filexyz = tempfile.NamedTemporaryFile(dir=self.temp_dir,
  1723. prefix="Tmp2", suffix=ext)
  1724. self.addCleanup(temp_filexyz.close)
  1725. # strip path and extension
  1726. program = os.path.basename(temp_filexyz.name)
  1727. program = os.path.splitext(program)[0]
  1728. with os_helper.EnvironmentVarGuard() as env:
  1729. env['PATHEXT'] = f"{ext};" # note the ;
  1730. rv = shutil.which(program, path=self.temp_dir)
  1731. self.assertEqual(rv, temp_filexyz.name)
  1732. class TestWhichBytes(TestWhich):
  1733. def setUp(self):
  1734. TestWhich.setUp(self)
  1735. self.dir = os.fsencode(self.dir)
  1736. self.file = os.fsencode(self.file)
  1737. self.temp_file.name = os.fsencode(self.temp_file.name)
  1738. self.curdir = os.fsencode(self.curdir)
  1739. self.ext = os.fsencode(self.ext)
  1740. class TestMove(BaseTest, unittest.TestCase):
  1741. def setUp(self):
  1742. filename = "foo"
  1743. self.src_dir = self.mkdtemp()
  1744. self.dst_dir = self.mkdtemp()
  1745. self.src_file = os.path.join(self.src_dir, filename)
  1746. self.dst_file = os.path.join(self.dst_dir, filename)
  1747. with open(self.src_file, "wb") as f:
  1748. f.write(b"spam")
  1749. def _check_move_file(self, src, dst, real_dst):
  1750. with open(src, "rb") as f:
  1751. contents = f.read()
  1752. shutil.move(src, dst)
  1753. with open(real_dst, "rb") as f:
  1754. self.assertEqual(contents, f.read())
  1755. self.assertFalse(os.path.exists(src))
  1756. def _check_move_dir(self, src, dst, real_dst):
  1757. contents = sorted(os.listdir(src))
  1758. shutil.move(src, dst)
  1759. self.assertEqual(contents, sorted(os.listdir(real_dst)))
  1760. self.assertFalse(os.path.exists(src))
  1761. def test_move_file(self):
  1762. # Move a file to another location on the same filesystem.
  1763. self._check_move_file(self.src_file, self.dst_file, self.dst_file)
  1764. def test_move_file_to_dir(self):
  1765. # Move a file inside an existing dir on the same filesystem.
  1766. self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
  1767. def test_move_file_to_dir_pathlike_src(self):
  1768. # Move a pathlike file to another location on the same filesystem.
  1769. src = pathlib.Path(self.src_file)
  1770. self._check_move_file(src, self.dst_dir, self.dst_file)
  1771. def test_move_file_to_dir_pathlike_dst(self):
  1772. # Move a file to another pathlike location on the same filesystem.
  1773. dst = pathlib.Path(self.dst_dir)
  1774. self._check_move_file(self.src_file, dst, self.dst_file)
  1775. @mock_rename
  1776. def test_move_file_other_fs(self):
  1777. # Move a file to an existing dir on another filesystem.
  1778. self.test_move_file()
  1779. @mock_rename
  1780. def test_move_file_to_dir_other_fs(self):
  1781. # Move a file to another location on another filesystem.
  1782. self.test_move_file_to_dir()
  1783. def test_move_dir(self):
  1784. # Move a dir to another location on the same filesystem.
  1785. dst_dir = tempfile.mktemp(dir=self.mkdtemp())
  1786. try:
  1787. self._check_move_dir(self.src_dir, dst_dir, dst_dir)
  1788. finally:
  1789. os_helper.rmtree(dst_dir)
  1790. @mock_rename
  1791. def test_move_dir_other_fs(self):
  1792. # Move a dir to another location on another filesystem.
  1793. self.test_move_dir()
  1794. def test_move_dir_to_dir(self):
  1795. # Move a dir inside an existing dir on the same filesystem.
  1796. self._check_move_dir(self.src_dir, self.dst_dir,
  1797. os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
  1798. @mock_rename
  1799. def test_move_dir_to_dir_other_fs(self):
  1800. # Move a dir inside an existing dir on another filesystem.
  1801. self.test_move_dir_to_dir()
  1802. def test_move_dir_sep_to_dir(self):
  1803. self._check_move_dir(self.src_dir + os.path.sep, self.dst_dir,
  1804. os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
  1805. @unittest.skipUnless(os.path.altsep, 'requires os.path.altsep')
  1806. def test_move_dir_altsep_to_dir(self):
  1807. self._check_move_dir(self.src_dir + os.path.altsep, self.dst_dir,
  1808. os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
  1809. def test_existing_file_inside_dest_dir(self):
  1810. # A file with the same name inside the destination dir already exists.
  1811. with open(self.dst_file, "wb"):
  1812. pass
  1813. self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
  1814. def test_dont_move_dir_in_itself(self):
  1815. # Moving a dir inside itself raises an Error.
  1816. dst = os.path.join(self.src_dir, "bar")
  1817. self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
  1818. def test_destinsrc_false_negative(self):
  1819. os.mkdir(TESTFN)
  1820. try:
  1821. for src, dst in [('srcdir', 'srcdir/dest')]:
  1822. src = os.path.join(TESTFN, src)
  1823. dst = os.path.join(TESTFN, dst)
  1824. self.assertTrue(shutil._destinsrc(src, dst),
  1825. msg='_destinsrc() wrongly concluded that '
  1826. 'dst (%s) is not in src (%s)' % (dst, src))
  1827. finally:
  1828. os_helper.rmtree(TESTFN)
  1829. def test_destinsrc_false_positive(self):
  1830. os.mkdir(TESTFN)
  1831. try:
  1832. for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
  1833. src = os.path.join(TESTFN, src)
  1834. dst = os.path.join(TESTFN, dst)
  1835. self.assertFalse(shutil._destinsrc(src, dst),
  1836. msg='_destinsrc() wrongly concluded that '
  1837. 'dst (%s) is in src (%s)' % (dst, src))
  1838. finally:
  1839. os_helper.rmtree(TESTFN)
  1840. @os_helper.skip_unless_symlink
  1841. @mock_rename
  1842. def test_move_file_symlink(self):
  1843. dst = os.path.join(self.src_dir, 'bar')
  1844. os.symlink(self.src_file, dst)
  1845. shutil.move(dst, self.dst_file)
  1846. self.assertTrue(os.path.islink(self.dst_file))
  1847. self.assertTrue(os.path.samefile(self.src_file, self.dst_file))
  1848. @os_helper.skip_unless_symlink
  1849. @mock_rename
  1850. def test_move_file_symlink_to_dir(self):
  1851. filename = "bar"
  1852. dst = os.path.join(self.src_dir, filename)
  1853. os.symlink(self.src_file, dst)
  1854. shutil.move(dst, self.dst_dir)
  1855. final_link = os.path.join(self.dst_dir, filename)
  1856. self.assertTrue(os.path.islink(final_link))
  1857. self.assertTrue(os.path.samefile(self.src_file, final_link))
  1858. @os_helper.skip_unless_symlink
  1859. @mock_rename
  1860. def test_move_dangling_symlink(self):
  1861. src = os.path.join(self.src_dir, 'baz')
  1862. dst = os.path.join(self.src_dir, 'bar')
  1863. os.symlink(src, dst)
  1864. dst_link = os.path.join(self.dst_dir, 'quux')
  1865. shutil.move(dst, dst_link)
  1866. self.assertTrue(os.path.islink(dst_link))
  1867. self.assertEqual(os.path.realpath(src), os.path.realpath(dst_link))
  1868. @os_helper.skip_unless_symlink
  1869. @mock_rename
  1870. def test_move_dir_symlink(self):
  1871. src = os.path.join(self.src_dir, 'baz')
  1872. dst = os.path.join(self.src_dir, 'bar')
  1873. os.mkdir(src)
  1874. os.symlink(src, dst)
  1875. dst_link = os.path.join(self.dst_dir, 'quux')
  1876. shutil.move(dst, dst_link)
  1877. self.assertTrue(os.path.islink(dst_link))
  1878. self.assertTrue(os.path.samefile(src, dst_link))
  1879. def test_move_return_value(self):
  1880. rv = shutil.move(self.src_file, self.dst_dir)
  1881. self.assertEqual(rv,
  1882. os.path.join(self.dst_dir, os.path.basename(self.src_file)))
  1883. def test_move_as_rename_return_value(self):
  1884. rv = shutil.move(self.src_file, os.path.join(self.dst_dir, 'bar'))
  1885. self.assertEqual(rv, os.path.join(self.dst_dir, 'bar'))
  1886. @mock_rename
  1887. def test_move_file_special_function(self):
  1888. moved = []
  1889. def _copy(src, dst):
  1890. moved.append((src, dst))
  1891. shutil.move(self.src_file, self.dst_dir, copy_function=_copy)
  1892. self.assertEqual(len(moved), 1)
  1893. @mock_rename
  1894. def test_move_dir_special_function(self):
  1895. moved = []
  1896. def _copy(src, dst):
  1897. moved.append((src, dst))
  1898. os_helper.create_empty_file(os.path.join(self.src_dir, 'child'))
  1899. os_helper.create_empty_file(os.path.join(self.src_dir, 'child1'))
  1900. shutil.move(self.src_dir, self.dst_dir, copy_function=_copy)
  1901. self.assertEqual(len(moved), 3)
  1902. def test_move_dir_caseinsensitive(self):
  1903. # Renames a folder to the same name
  1904. # but a different case.
  1905. self.src_dir = self.mkdtemp()
  1906. dst_dir = os.path.join(
  1907. os.path.dirname(self.src_dir),
  1908. os.path.basename(self.src_dir).upper())
  1909. self.assertNotEqual(self.src_dir, dst_dir)
  1910. try:
  1911. shutil.move(self.src_dir, dst_dir)
  1912. self.assertTrue(os.path.isdir(dst_dir))
  1913. finally:
  1914. os.rmdir(dst_dir)
  1915. @os_helper.skip_unless_dac_override
  1916. @unittest.skipUnless(hasattr(os, 'lchflags')
  1917. and hasattr(stat, 'SF_IMMUTABLE')
  1918. and hasattr(stat, 'UF_OPAQUE'),
  1919. 'requires lchflags')
  1920. def test_move_dir_permission_denied(self):
  1921. # bpo-42782: shutil.move should not create destination directories
  1922. # if the source directory cannot be removed.
  1923. try:
  1924. os.mkdir(TESTFN_SRC)
  1925. os.lchflags(TESTFN_SRC, stat.SF_IMMUTABLE)
  1926. # Testing on an empty immutable directory
  1927. # TESTFN_DST should not exist if shutil.move failed
  1928. self.assertRaises(PermissionError, shutil.move, TESTFN_SRC, TESTFN_DST)
  1929. self.assertFalse(TESTFN_DST in os.listdir())
  1930. # Create a file and keep the directory immutable
  1931. os.lchflags(TESTFN_SRC, stat.UF_OPAQUE)
  1932. os_helper.create_empty_file(os.path.join(TESTFN_SRC, 'child'))
  1933. os.lchflags(TESTFN_SRC, stat.SF_IMMUTABLE)
  1934. # Testing on a non-empty immutable directory
  1935. # TESTFN_DST should not exist if shutil.move failed
  1936. self.assertRaises(PermissionError, shutil.move, TESTFN_SRC, TESTFN_DST)
  1937. self.assertFalse(TESTFN_DST in os.listdir())
  1938. finally:
  1939. if os.path.exists(TESTFN_SRC):
  1940. os.lchflags(TESTFN_SRC, stat.UF_OPAQUE)
  1941. os_helper.rmtree(TESTFN_SRC)
  1942. if os.path.exists(TESTFN_DST):
  1943. os.lchflags(TESTFN_DST, stat.UF_OPAQUE)
  1944. os_helper.rmtree(TESTFN_DST)
  1945. class TestCopyFile(unittest.TestCase):
  1946. class Faux(object):
  1947. _entered = False
  1948. _exited_with = None
  1949. _raised = False
  1950. def __init__(self, raise_in_exit=False, suppress_at_exit=True):
  1951. self._raise_in_exit = raise_in_exit
  1952. self._suppress_at_exit = suppress_at_exit
  1953. def read(self, *args):
  1954. return ''
  1955. def __enter__(self):
  1956. self._entered = True
  1957. def __exit__(self, exc_type, exc_val, exc_tb):
  1958. self._exited_with = exc_type, exc_val, exc_tb
  1959. if self._raise_in_exit:
  1960. self._raised = True
  1961. raise OSError("Cannot close")
  1962. return self._suppress_at_exit
  1963. def test_w_source_open_fails(self):
  1964. def _open(filename, mode='r'):
  1965. if filename == 'srcfile':
  1966. raise OSError('Cannot open "srcfile"')
  1967. assert 0 # shouldn't reach here.
  1968. with support.swap_attr(shutil, 'open', _open):
  1969. with self.assertRaises(OSError):
  1970. shutil.copyfile('srcfile', 'destfile')
  1971. @unittest.skipIf(MACOS, "skipped on macOS")
  1972. def test_w_dest_open_fails(self):
  1973. srcfile = self.Faux()
  1974. def _open(filename, mode='r'):
  1975. if filename == 'srcfile':
  1976. return srcfile
  1977. if filename == 'destfile':
  1978. raise OSError('Cannot open "destfile"')
  1979. assert 0 # shouldn't reach here.
  1980. with support.swap_attr(shutil, 'open', _open):
  1981. shutil.copyfile('srcfile', 'destfile')
  1982. self.assertTrue(srcfile._entered)
  1983. self.assertTrue(srcfile._exited_with[0] is OSError)
  1984. self.assertEqual(srcfile._exited_with[1].args,
  1985. ('Cannot open "destfile"',))
  1986. @unittest.skipIf(MACOS, "skipped on macOS")
  1987. def test_w_dest_close_fails(self):
  1988. srcfile = self.Faux()
  1989. destfile = self.Faux(True)
  1990. def _open(filename, mode='r'):
  1991. if filename == 'srcfile':
  1992. return srcfile
  1993. if filename == 'destfile':
  1994. return destfile
  1995. assert 0 # shouldn't reach here.
  1996. with support.swap_attr(shutil, 'open', _open):
  1997. shutil.copyfile('srcfile', 'destfile')
  1998. self.assertTrue(srcfile._entered)
  1999. self.assertTrue(destfile._entered)
  2000. self.assertTrue(destfile._raised)
  2001. self.assertTrue(srcfile._exited_with[0] is OSError)
  2002. self.assertEqual(srcfile._exited_with[1].args,
  2003. ('Cannot close',))
  2004. @unittest.skipIf(MACOS, "skipped on macOS")
  2005. def test_w_source_close_fails(self):
  2006. srcfile = self.Faux(True)
  2007. destfile = self.Faux()
  2008. def _open(filename, mode='r'):
  2009. if filename == 'srcfile':
  2010. return srcfile
  2011. if filename == 'destfile':
  2012. return destfile
  2013. assert 0 # shouldn't reach here.
  2014. with support.swap_attr(shutil, 'open', _open):
  2015. with self.assertRaises(OSError):
  2016. shutil.copyfile('srcfile', 'destfile')
  2017. self.assertTrue(srcfile._entered)
  2018. self.assertTrue(destfile._entered)
  2019. self.assertFalse(destfile._raised)
  2020. self.assertTrue(srcfile._exited_with[0] is None)
  2021. self.assertTrue(srcfile._raised)
  2022. class TestCopyFileObj(unittest.TestCase):
  2023. FILESIZE = 2 * 1024 * 1024
  2024. @classmethod
  2025. def setUpClass(cls):
  2026. write_test_file(TESTFN, cls.FILESIZE)
  2027. @classmethod
  2028. def tearDownClass(cls):
  2029. os_helper.unlink(TESTFN)
  2030. os_helper.unlink(TESTFN2)
  2031. def tearDown(self):
  2032. os_helper.unlink(TESTFN2)
  2033. @contextlib.contextmanager
  2034. def get_files(self):
  2035. with open(TESTFN, "rb") as src:
  2036. with open(TESTFN2, "wb") as dst:
  2037. yield (src, dst)
  2038. def assert_files_eq(self, src, dst):
  2039. with open(src, 'rb') as fsrc:
  2040. with open(dst, 'rb') as fdst:
  2041. self.assertEqual(fsrc.read(), fdst.read())
  2042. def test_content(self):
  2043. with self.get_files() as (src, dst):
  2044. shutil.copyfileobj(src, dst)
  2045. self.assert_files_eq(TESTFN, TESTFN2)
  2046. def test_file_not_closed(self):
  2047. with self.get_files() as (src, dst):
  2048. shutil.copyfileobj(src, dst)
  2049. assert not src.closed
  2050. assert not dst.closed
  2051. def test_file_offset(self):
  2052. with self.get_files() as (src, dst):
  2053. shutil.copyfileobj(src, dst)
  2054. self.assertEqual(src.tell(), self.FILESIZE)
  2055. self.assertEqual(dst.tell(), self.FILESIZE)
  2056. @unittest.skipIf(os.name != 'nt', "Windows only")
  2057. def test_win_impl(self):
  2058. # Make sure alternate Windows implementation is called.
  2059. with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
  2060. shutil.copyfile(TESTFN, TESTFN2)
  2061. assert m.called
  2062. # File size is 2 MiB but max buf size should be 1 MiB.
  2063. self.assertEqual(m.call_args[0][2], 1 * 1024 * 1024)
  2064. # If file size < 1 MiB memoryview() length must be equal to
  2065. # the actual file size.
  2066. with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f:
  2067. f.write(b'foo')
  2068. fname = f.name
  2069. self.addCleanup(os_helper.unlink, fname)
  2070. with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
  2071. shutil.copyfile(fname, TESTFN2)
  2072. self.assertEqual(m.call_args[0][2], 3)
  2073. # Empty files should not rely on readinto() variant.
  2074. with tempfile.NamedTemporaryFile(dir=os.getcwd(), delete=False) as f:
  2075. pass
  2076. fname = f.name
  2077. self.addCleanup(os_helper.unlink, fname)
  2078. with unittest.mock.patch("shutil._copyfileobj_readinto") as m:
  2079. shutil.copyfile(fname, TESTFN2)
  2080. assert not m.called
  2081. self.assert_files_eq(fname, TESTFN2)
  2082. class _ZeroCopyFileTest(object):
  2083. """Tests common to all zero-copy APIs."""
  2084. FILESIZE = (10 * 1024 * 1024) # 10 MiB
  2085. FILEDATA = b""
  2086. PATCHPOINT = ""
  2087. @classmethod
  2088. def setUpClass(cls):
  2089. write_test_file(TESTFN, cls.FILESIZE)
  2090. with open(TESTFN, 'rb') as f:
  2091. cls.FILEDATA = f.read()
  2092. assert len(cls.FILEDATA) == cls.FILESIZE
  2093. @classmethod
  2094. def tearDownClass(cls):
  2095. os_helper.unlink(TESTFN)
  2096. def tearDown(self):
  2097. os_helper.unlink(TESTFN2)
  2098. @contextlib.contextmanager
  2099. def get_files(self):
  2100. with open(TESTFN, "rb") as src:
  2101. with open(TESTFN2, "wb") as dst:
  2102. yield (src, dst)
  2103. def zerocopy_fun(self, *args, **kwargs):
  2104. raise NotImplementedError("must be implemented in subclass")
  2105. def reset(self):
  2106. self.tearDown()
  2107. self.tearDownClass()
  2108. self.setUpClass()
  2109. self.setUp()
  2110. # ---
  2111. def test_regular_copy(self):
  2112. with self.get_files() as (src, dst):
  2113. self.zerocopy_fun(src, dst)
  2114. self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
  2115. # Make sure the fallback function is not called.
  2116. with self.get_files() as (src, dst):
  2117. with unittest.mock.patch('shutil.copyfileobj') as m:
  2118. shutil.copyfile(TESTFN, TESTFN2)
  2119. assert not m.called
  2120. def test_same_file(self):
  2121. self.addCleanup(self.reset)
  2122. with self.get_files() as (src, dst):
  2123. with self.assertRaises(Exception):
  2124. self.zerocopy_fun(src, src)
  2125. # Make sure src file is not corrupted.
  2126. self.assertEqual(read_file(TESTFN, binary=True), self.FILEDATA)
  2127. def test_non_existent_src(self):
  2128. name = tempfile.mktemp(dir=os.getcwd())
  2129. with self.assertRaises(FileNotFoundError) as cm:
  2130. shutil.copyfile(name, "new")
  2131. self.assertEqual(cm.exception.filename, name)
  2132. def test_empty_file(self):
  2133. srcname = TESTFN + 'src'
  2134. dstname = TESTFN + 'dst'
  2135. self.addCleanup(lambda: os_helper.unlink(srcname))
  2136. self.addCleanup(lambda: os_helper.unlink(dstname))
  2137. with open(srcname, "wb"):
  2138. pass
  2139. with open(srcname, "rb") as src:
  2140. with open(dstname, "wb") as dst:
  2141. self.zerocopy_fun(src, dst)
  2142. self.assertEqual(read_file(dstname, binary=True), b"")
  2143. def test_unhandled_exception(self):
  2144. with unittest.mock.patch(self.PATCHPOINT,
  2145. side_effect=ZeroDivisionError):
  2146. self.assertRaises(ZeroDivisionError,
  2147. shutil.copyfile, TESTFN, TESTFN2)
  2148. def test_exception_on_first_call(self):
  2149. # Emulate a case where the first call to the zero-copy
  2150. # function raises an exception in which case the function is
  2151. # supposed to give up immediately.
  2152. with unittest.mock.patch(self.PATCHPOINT,
  2153. side_effect=OSError(errno.EINVAL, "yo")):
  2154. with self.get_files() as (src, dst):
  2155. with self.assertRaises(_GiveupOnFastCopy):
  2156. self.zerocopy_fun(src, dst)
  2157. def test_filesystem_full(self):
  2158. # Emulate a case where filesystem is full and sendfile() fails
  2159. # on first call.
  2160. with unittest.mock.patch(self.PATCHPOINT,
  2161. side_effect=OSError(errno.ENOSPC, "yo")):
  2162. with self.get_files() as (src, dst):
  2163. self.assertRaises(OSError, self.zerocopy_fun, src, dst)
  2164. @unittest.skipIf(not SUPPORTS_SENDFILE, 'os.sendfile() not supported')
  2165. class TestZeroCopySendfile(_ZeroCopyFileTest, unittest.TestCase):
  2166. PATCHPOINT = "os.sendfile"
  2167. def zerocopy_fun(self, fsrc, fdst):
  2168. return shutil._fastcopy_sendfile(fsrc, fdst)
  2169. def test_non_regular_file_src(self):
  2170. with io.BytesIO(self.FILEDATA) as src:
  2171. with open(TESTFN2, "wb") as dst:
  2172. with self.assertRaises(_GiveupOnFastCopy):
  2173. self.zerocopy_fun(src, dst)
  2174. shutil.copyfileobj(src, dst)
  2175. self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
  2176. def test_non_regular_file_dst(self):
  2177. with open(TESTFN, "rb") as src:
  2178. with io.BytesIO() as dst:
  2179. with self.assertRaises(_GiveupOnFastCopy):
  2180. self.zerocopy_fun(src, dst)
  2181. shutil.copyfileobj(src, dst)
  2182. dst.seek(0)
  2183. self.assertEqual(dst.read(), self.FILEDATA)
  2184. def test_exception_on_second_call(self):
  2185. def sendfile(*args, **kwargs):
  2186. if not flag:
  2187. flag.append(None)
  2188. return orig_sendfile(*args, **kwargs)
  2189. else:
  2190. raise OSError(errno.EBADF, "yo")
  2191. flag = []
  2192. orig_sendfile = os.sendfile
  2193. with unittest.mock.patch('os.sendfile', create=True,
  2194. side_effect=sendfile):
  2195. with self.get_files() as (src, dst):
  2196. with self.assertRaises(OSError) as cm:
  2197. shutil._fastcopy_sendfile(src, dst)
  2198. assert flag
  2199. self.assertEqual(cm.exception.errno, errno.EBADF)
  2200. def test_cant_get_size(self):
  2201. # Emulate a case where src file size cannot be determined.
  2202. # Internally bufsize will be set to a small value and
  2203. # sendfile() will be called repeatedly.
  2204. with unittest.mock.patch('os.fstat', side_effect=OSError) as m:
  2205. with self.get_files() as (src, dst):
  2206. shutil._fastcopy_sendfile(src, dst)
  2207. assert m.called
  2208. self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
  2209. def test_small_chunks(self):
  2210. # Force internal file size detection to be smaller than the
  2211. # actual file size. We want to force sendfile() to be called
  2212. # multiple times, also in order to emulate a src fd which gets
  2213. # bigger while it is being copied.
  2214. mock = unittest.mock.Mock()
  2215. mock.st_size = 65536 + 1
  2216. with unittest.mock.patch('os.fstat', return_value=mock) as m:
  2217. with self.get_files() as (src, dst):
  2218. shutil._fastcopy_sendfile(src, dst)
  2219. assert m.called
  2220. self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
  2221. def test_big_chunk(self):
  2222. # Force internal file size detection to be +100MB bigger than
  2223. # the actual file size. Make sure sendfile() does not rely on
  2224. # file size value except for (maybe) a better throughput /
  2225. # performance.
  2226. mock = unittest.mock.Mock()
  2227. mock.st_size = self.FILESIZE + (100 * 1024 * 1024)
  2228. with unittest.mock.patch('os.fstat', return_value=mock) as m:
  2229. with self.get_files() as (src, dst):
  2230. shutil._fastcopy_sendfile(src, dst)
  2231. assert m.called
  2232. self.assertEqual(read_file(TESTFN2, binary=True), self.FILEDATA)
  2233. def test_blocksize_arg(self):
  2234. with unittest.mock.patch('os.sendfile',
  2235. side_effect=ZeroDivisionError) as m:
  2236. self.assertRaises(ZeroDivisionError,
  2237. shutil.copyfile, TESTFN, TESTFN2)
  2238. blocksize = m.call_args[0][3]
  2239. # Make sure file size and the block size arg passed to
  2240. # sendfile() are the same.
  2241. self.assertEqual(blocksize, os.path.getsize(TESTFN))
  2242. # ...unless we're dealing with a small file.
  2243. os_helper.unlink(TESTFN2)
  2244. write_file(TESTFN2, b"hello", binary=True)
  2245. self.addCleanup(os_helper.unlink, TESTFN2 + '3')
  2246. self.assertRaises(ZeroDivisionError,
  2247. shutil.copyfile, TESTFN2, TESTFN2 + '3')
  2248. blocksize = m.call_args[0][3]
  2249. self.assertEqual(blocksize, 2 ** 23)
  2250. def test_file2file_not_supported(self):
  2251. # Emulate a case where sendfile() only support file->socket
  2252. # fds. In such a case copyfile() is supposed to skip the
  2253. # fast-copy attempt from then on.
  2254. assert shutil._USE_CP_SENDFILE
  2255. try:
  2256. with unittest.mock.patch(
  2257. self.PATCHPOINT,
  2258. side_effect=OSError(errno.ENOTSOCK, "yo")) as m:
  2259. with self.get_files() as (src, dst):
  2260. with self.assertRaises(_GiveupOnFastCopy):
  2261. shutil._fastcopy_sendfile(src, dst)
  2262. assert m.called
  2263. assert not shutil._USE_CP_SENDFILE
  2264. with unittest.mock.patch(self.PATCHPOINT) as m:
  2265. shutil.copyfile(TESTFN, TESTFN2)
  2266. assert not m.called
  2267. finally:
  2268. shutil._USE_CP_SENDFILE = True
  2269. @unittest.skipIf(not MACOS, 'macOS only')
  2270. class TestZeroCopyMACOS(_ZeroCopyFileTest, unittest.TestCase):
  2271. PATCHPOINT = "posix._fcopyfile"
  2272. def zerocopy_fun(self, src, dst):
  2273. return shutil._fastcopy_fcopyfile(src, dst, posix._COPYFILE_DATA)
  2274. class TestGetTerminalSize(unittest.TestCase):
  2275. def test_does_not_crash(self):
  2276. """Check if get_terminal_size() returns a meaningful value.
  2277. There's no easy portable way to actually check the size of the
  2278. terminal, so let's check if it returns something sensible instead.
  2279. """
  2280. size = shutil.get_terminal_size()
  2281. self.assertGreaterEqual(size.columns, 0)
  2282. self.assertGreaterEqual(size.lines, 0)
  2283. def test_os_environ_first(self):
  2284. "Check if environment variables have precedence"
  2285. with os_helper.EnvironmentVarGuard() as env:
  2286. env['COLUMNS'] = '777'
  2287. del env['LINES']
  2288. size = shutil.get_terminal_size()
  2289. self.assertEqual(size.columns, 777)
  2290. with os_helper.EnvironmentVarGuard() as env:
  2291. del env['COLUMNS']
  2292. env['LINES'] = '888'
  2293. size = shutil.get_terminal_size()
  2294. self.assertEqual(size.lines, 888)
  2295. def test_bad_environ(self):
  2296. with os_helper.EnvironmentVarGuard() as env:
  2297. env['COLUMNS'] = 'xxx'
  2298. env['LINES'] = 'yyy'
  2299. size = shutil.get_terminal_size()
  2300. self.assertGreaterEqual(size.columns, 0)
  2301. self.assertGreaterEqual(size.lines, 0)
  2302. @unittest.skipUnless(os.isatty(sys.__stdout__.fileno()), "not on tty")
  2303. @unittest.skipUnless(hasattr(os, 'get_terminal_size'),
  2304. 'need os.get_terminal_size()')
  2305. def test_stty_match(self):
  2306. """Check if stty returns the same results ignoring env
  2307. This test will fail if stdin and stdout are connected to
  2308. different terminals with different sizes. Nevertheless, such
  2309. situations should be pretty rare.
  2310. """
  2311. try:
  2312. size = subprocess.check_output(['stty', 'size']).decode().split()
  2313. except (FileNotFoundError, PermissionError,
  2314. subprocess.CalledProcessError):
  2315. self.skipTest("stty invocation failed")
  2316. expected = (int(size[1]), int(size[0])) # reversed order
  2317. with os_helper.EnvironmentVarGuard() as env:
  2318. del env['LINES']
  2319. del env['COLUMNS']
  2320. actual = shutil.get_terminal_size()
  2321. self.assertEqual(expected, actual)
  2322. @unittest.skipIf(support.is_wasi, "WASI has no /dev/null")
  2323. def test_fallback(self):
  2324. with os_helper.EnvironmentVarGuard() as env:
  2325. del env['LINES']
  2326. del env['COLUMNS']
  2327. # sys.__stdout__ has no fileno()
  2328. with support.swap_attr(sys, '__stdout__', None):
  2329. size = shutil.get_terminal_size(fallback=(10, 20))
  2330. self.assertEqual(size.columns, 10)
  2331. self.assertEqual(size.lines, 20)
  2332. # sys.__stdout__ is not a terminal on Unix
  2333. # or fileno() not in (0, 1, 2) on Windows
  2334. with open(os.devnull, 'w', encoding='utf-8') as f, \
  2335. support.swap_attr(sys, '__stdout__', f):
  2336. size = shutil.get_terminal_size(fallback=(30, 40))
  2337. self.assertEqual(size.columns, 30)
  2338. self.assertEqual(size.lines, 40)
  2339. class PublicAPITests(unittest.TestCase):
  2340. """Ensures that the correct values are exposed in the public API."""
  2341. def test_module_all_attribute(self):
  2342. self.assertTrue(hasattr(shutil, '__all__'))
  2343. target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
  2344. 'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
  2345. 'SpecialFileError', 'ExecError', 'make_archive',
  2346. 'get_archive_formats', 'register_archive_format',
  2347. 'unregister_archive_format', 'get_unpack_formats',
  2348. 'register_unpack_format', 'unregister_unpack_format',
  2349. 'unpack_archive', 'ignore_patterns', 'chown', 'which',
  2350. 'get_terminal_size', 'SameFileError']
  2351. if hasattr(os, 'statvfs') or os.name == 'nt':
  2352. target_api.append('disk_usage')
  2353. self.assertEqual(set(shutil.__all__), set(target_api))
  2354. if __name__ == '__main__':
  2355. unittest.main()