Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_paths.py 69KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Test cases covering L{twisted.python.filepath}.
  5. """
  6. import errno
  7. import os
  8. import pickle
  9. import stat
  10. import time
  11. from pprint import pformat
  12. from unittest import skipIf
  13. from zope.interface.verify import verifyObject
  14. from twisted.python import filepath
  15. from twisted.python.runtime import platform
  16. from twisted.python.win32 import ERROR_DIRECTORY
  17. from twisted.trial.unittest import SynchronousTestCase as TestCase
  18. symlinkSkip = not platform._supportsSymlinks()
  19. class BytesTestCase(TestCase):
  20. """
  21. Override default method implementations to support byte paths.
  22. """
  23. def mktemp(self):
  24. """
  25. Return a temporary path, encoded as bytes.
  26. """
  27. return TestCase.mktemp(self).encode("utf-8")
  28. class AbstractFilePathTests(BytesTestCase):
  29. """
  30. Tests for L{IFilePath} implementations.
  31. """
  32. f1content = b"file 1"
  33. f2content = b"file 2"
  34. def _mkpath(self, *p):
  35. x = os.path.abspath(os.path.join(self.cmn, *p))
  36. self.all.append(x)
  37. return x
  38. def subdir(self, *dirname):
  39. os.mkdir(self._mkpath(*dirname))
  40. def subfile(self, *dirname):
  41. return open(self._mkpath(*dirname), "wb")
  42. def setUp(self):
  43. self.now = time.time()
  44. cmn = self.cmn = os.path.abspath(self.mktemp())
  45. self.all = [cmn]
  46. os.mkdir(cmn)
  47. self.subdir(b"sub1")
  48. with self.subfile(b"file1") as f:
  49. f.write(self.f1content)
  50. with self.subfile(b"sub1", b"file2") as f:
  51. f.write(self.f2content)
  52. self.subdir(b"sub3")
  53. self.subfile(b"sub3", b"file3.ext1").close()
  54. self.subfile(b"sub3", b"file3.ext2").close()
  55. self.subfile(b"sub3", b"file3.ext3").close()
  56. self.path = filepath.FilePath(cmn)
  57. self.root = filepath.FilePath(b"/")
  58. def test_verifyObject(self):
  59. """
  60. Instances of the path type being tested provide L{IFilePath}.
  61. """
  62. self.assertTrue(verifyObject(filepath.IFilePath, self.path))
  63. def test_segmentsFromPositive(self):
  64. """
  65. Verify that the segments between two paths are correctly identified.
  66. """
  67. self.assertEqual(
  68. self.path.child(b"a").child(b"b").child(b"c").segmentsFrom(self.path),
  69. [b"a", b"b", b"c"],
  70. )
  71. def test_segmentsFromNegative(self):
  72. """
  73. Verify that segmentsFrom notices when the ancestor isn't an ancestor.
  74. """
  75. self.assertRaises(
  76. ValueError,
  77. self.path.child(b"a").child(b"b").child(b"c").segmentsFrom,
  78. self.path.child(b"d").child(b"c").child(b"e"),
  79. )
  80. def test_walk(self):
  81. """
  82. Verify that walking the path gives the same result as the known file
  83. hierarchy.
  84. """
  85. x = [foo.path for foo in self.path.walk()]
  86. self.assertEqual(set(x), set(self.all))
  87. def test_parents(self):
  88. """
  89. L{FilePath.parents()} should return an iterator of every ancestor of
  90. the L{FilePath} in question.
  91. """
  92. L = []
  93. pathobj = self.path.child(b"a").child(b"b").child(b"c")
  94. fullpath = pathobj.path
  95. lastpath = fullpath
  96. thispath = os.path.dirname(fullpath)
  97. while lastpath != self.root.path:
  98. L.append(thispath)
  99. lastpath = thispath
  100. thispath = os.path.dirname(thispath)
  101. self.assertEqual([x.path for x in pathobj.parents()], L)
  102. def test_validSubdir(self):
  103. """
  104. Verify that a valid subdirectory will show up as a directory, but not as a
  105. file, not as a symlink, and be listable.
  106. """
  107. sub1 = self.path.child(b"sub1")
  108. self.assertTrue(sub1.exists(), "This directory does exist.")
  109. self.assertTrue(sub1.isdir(), "It's a directory.")
  110. self.assertFalse(sub1.isfile(), "It's a directory.")
  111. self.assertFalse(sub1.islink(), "It's a directory.")
  112. self.assertEqual(sub1.listdir(), [b"file2"])
  113. def test_invalidSubdir(self):
  114. """
  115. Verify that a subdirectory that doesn't exist is reported as such.
  116. """
  117. sub2 = self.path.child(b"sub2")
  118. self.assertFalse(sub2.exists(), "This directory does not exist.")
  119. def test_validFiles(self):
  120. """
  121. Make sure that we can read existent non-empty files.
  122. """
  123. f1 = self.path.child(b"file1")
  124. with f1.open() as f:
  125. self.assertEqual(f.read(), self.f1content)
  126. f2 = self.path.child(b"sub1").child(b"file2")
  127. with f2.open() as f:
  128. self.assertEqual(f.read(), self.f2content)
  129. def test_multipleChildSegments(self):
  130. """
  131. C{fp.descendant([a, b, c])} returns the same L{FilePath} as is returned
  132. by C{fp.child(a).child(b).child(c)}.
  133. """
  134. multiple = self.path.descendant([b"a", b"b", b"c"])
  135. single = self.path.child(b"a").child(b"b").child(b"c")
  136. self.assertEqual(multiple, single)
  137. def test_dictionaryKeys(self):
  138. """
  139. Verify that path instances are usable as dictionary keys.
  140. """
  141. f1 = self.path.child(b"file1")
  142. f1prime = self.path.child(b"file1")
  143. f2 = self.path.child(b"file2")
  144. dictoid = {}
  145. dictoid[f1] = 3
  146. dictoid[f1prime] = 4
  147. self.assertEqual(dictoid[f1], 4)
  148. self.assertEqual(list(dictoid.keys()), [f1])
  149. self.assertIs(list(dictoid.keys())[0], f1)
  150. self.assertIsNot(list(dictoid.keys())[0], f1prime) # sanity check
  151. dictoid[f2] = 5
  152. self.assertEqual(dictoid[f2], 5)
  153. self.assertEqual(len(dictoid), 2)
  154. def test_dictionaryKeyWithString(self):
  155. """
  156. Verify that path instances are usable as dictionary keys which do not clash
  157. with their string counterparts.
  158. """
  159. f1 = self.path.child(b"file1")
  160. dictoid = {f1: "hello"}
  161. dictoid[f1.path] = "goodbye"
  162. self.assertEqual(len(dictoid), 2)
  163. def test_childrenNonexistentError(self):
  164. """
  165. Verify that children raises the appropriate exception for non-existent
  166. directories.
  167. """
  168. self.assertRaises(
  169. filepath.UnlistableError, self.path.child(b"not real").children
  170. )
  171. def test_childrenNotDirectoryError(self):
  172. """
  173. Verify that listdir raises the appropriate exception for attempting to list
  174. a file rather than a directory.
  175. """
  176. self.assertRaises(filepath.UnlistableError, self.path.child(b"file1").children)
  177. def test_newTimesAreFloats(self):
  178. """
  179. Verify that all times returned from the various new time functions are ints
  180. (and hopefully therefore 'high precision').
  181. """
  182. for p in self.path, self.path.child(b"file1"):
  183. self.assertEqual(type(p.getAccessTime()), float)
  184. self.assertEqual(type(p.getModificationTime()), float)
  185. self.assertEqual(type(p.getStatusChangeTime()), float)
  186. def test_oldTimesAreInts(self):
  187. """
  188. Verify that all times returned from the various time functions are
  189. integers, for compatibility.
  190. """
  191. for p in self.path, self.path.child(b"file1"):
  192. self.assertEqual(type(p.getatime()), int)
  193. self.assertEqual(type(p.getmtime()), int)
  194. self.assertEqual(type(p.getctime()), int)
  195. class FakeWindowsPath(filepath.FilePath):
  196. """
  197. A test version of FilePath which overrides listdir to raise L{WindowsError}.
  198. """
  199. def listdir(self):
  200. """
  201. @raise WindowsError: always.
  202. """
  203. # For Python 3.3 and higher, WindowsError is an alias for OSError.
  204. # The first argument to the OSError constructor is errno,
  205. # and the fourth argument is winerror.
  206. # For further details, refer to:
  207. # https://docs.python.org/3/library/exceptions.html#OSError
  208. #
  209. # On Windows, if winerror is set in the constructor,
  210. # the errno value in the constructor is ignored, and OSError internally
  211. # maps the winerror value to an errno value.
  212. raise OSError(
  213. None,
  214. "A directory's validness was called into question",
  215. self.path,
  216. ERROR_DIRECTORY,
  217. )
  218. class ListingCompatibilityTests(BytesTestCase):
  219. """
  220. These tests verify compatibility with legacy behavior of directory listing.
  221. """
  222. @skipIf(not platform.isWindows(), "Only relevant on on Windows.")
  223. def test_windowsErrorExcept(self):
  224. """
  225. Verify that when a WindowsError is raised from listdir, catching
  226. WindowsError works.
  227. """
  228. fwp = FakeWindowsPath(self.mktemp())
  229. self.assertRaises(filepath.UnlistableError, fwp.children)
  230. self.assertRaises(WindowsError, fwp.children)
  231. def test_alwaysCatchOSError(self):
  232. """
  233. Verify that in the normal case where a directory does not exist, we will
  234. get an OSError.
  235. """
  236. fp = filepath.FilePath(self.mktemp())
  237. self.assertRaises(OSError, fp.children)
  238. def test_keepOriginalAttributes(self):
  239. """
  240. Verify that the Unlistable exception raised will preserve the attributes of
  241. the previously-raised exception.
  242. """
  243. fp = filepath.FilePath(self.mktemp())
  244. ose = self.assertRaises(OSError, fp.children)
  245. d1 = list(ose.__dict__.keys())
  246. d1.remove("originalException")
  247. d2 = list(ose.originalException.__dict__.keys())
  248. d1.sort()
  249. d2.sort()
  250. self.assertEqual(d1, d2)
  251. class ExplodingFile:
  252. """
  253. A C{file}-alike which raises exceptions from its I/O methods and keeps track
  254. of whether it has been closed.
  255. @ivar closed: A C{bool} which is C{False} until C{close} is called, then it
  256. is C{True}.
  257. """
  258. closed = False
  259. def read(self, n=0):
  260. """
  261. @raise IOError: Always raised.
  262. """
  263. raise OSError()
  264. def write(self, what):
  265. """
  266. @raise IOError: Always raised.
  267. """
  268. raise OSError()
  269. def close(self):
  270. """
  271. Mark the file as having been closed.
  272. """
  273. self.closed = True
  274. def __enter__(self):
  275. return self
  276. def __exit__(self, exc_type, exc_value, traceback):
  277. self.close()
  278. class TrackingFilePath(filepath.FilePath):
  279. """
  280. A subclass of L{filepath.FilePath} which maintains a list of all other paths
  281. created by clonePath.
  282. @ivar trackingList: A list of all paths created by this path via
  283. C{clonePath} (which also includes paths created by methods like
  284. C{parent}, C{sibling}, C{child}, etc (and all paths subsequently created
  285. by those paths, etc).
  286. @type trackingList: C{list} of L{TrackingFilePath}
  287. @ivar openedFiles: A list of all file objects opened by this
  288. L{TrackingFilePath} or any other L{TrackingFilePath} in C{trackingList}.
  289. @type openedFiles: C{list} of C{file}
  290. """
  291. def __init__(self, path, alwaysCreate=False, trackingList=None):
  292. filepath.FilePath.__init__(self, path, alwaysCreate)
  293. if trackingList is None:
  294. trackingList = []
  295. self.trackingList = trackingList
  296. self.openedFiles = []
  297. def open(self, *a, **k):
  298. """
  299. Override 'open' to track all files opened by this path.
  300. """
  301. f = filepath.FilePath.open(self, *a, **k)
  302. self.openedFiles.append(f)
  303. return f
  304. def openedPaths(self):
  305. """
  306. Return a list of all L{TrackingFilePath}s associated with this
  307. L{TrackingFilePath} that have had their C{open()} method called.
  308. """
  309. return [path for path in self.trackingList if path.openedFiles]
  310. def clonePath(self, name):
  311. """
  312. Override L{filepath.FilePath.clonePath} to give the new path a reference
  313. to the same tracking list.
  314. """
  315. clone = TrackingFilePath(name, trackingList=self.trackingList)
  316. self.trackingList.append(clone)
  317. return clone
  318. class ExplodingFilePath(filepath.FilePath):
  319. """
  320. A specialized L{FilePath} which always returns an instance of
  321. L{ExplodingFile} from its C{open} method.
  322. @ivar fp: The L{ExplodingFile} instance most recently returned from the
  323. C{open} method.
  324. """
  325. def __init__(self, pathName, originalExploder=None):
  326. """
  327. Initialize an L{ExplodingFilePath} with a name and a reference to the
  328. @param pathName: The path name as passed to L{filepath.FilePath}.
  329. @type pathName: C{str}
  330. @param originalExploder: The L{ExplodingFilePath} to associate opened
  331. files with.
  332. @type originalExploder: L{ExplodingFilePath}
  333. """
  334. filepath.FilePath.__init__(self, pathName)
  335. if originalExploder is None:
  336. originalExploder = self
  337. self._originalExploder = originalExploder
  338. def open(self, mode=None):
  339. """
  340. Create, save, and return a new C{ExplodingFile}.
  341. @param mode: Present for signature compatibility. Ignored.
  342. @return: A new C{ExplodingFile}.
  343. """
  344. f = self._originalExploder.fp = ExplodingFile()
  345. return f
  346. def clonePath(self, name):
  347. return ExplodingFilePath(name, self._originalExploder)
  348. class PermissionsTests(BytesTestCase):
  349. """
  350. Test Permissions and RWX classes
  351. """
  352. def assertNotUnequal(self, first, second, msg=None):
  353. """
  354. Tests that C{first} != C{second} is false. This method tests the
  355. __ne__ method, as opposed to L{assertEqual} (C{first} == C{second}),
  356. which tests the __eq__ method.
  357. Note: this should really be part of trial
  358. """
  359. if first != second:
  360. if msg is None:
  361. msg = ""
  362. if len(msg) > 0:
  363. msg += "\n"
  364. raise self.failureException(
  365. "%snot not unequal (__ne__ not implemented correctly):"
  366. "\na = %s\nb = %s\n" % (msg, pformat(first), pformat(second))
  367. )
  368. return first
  369. def test_rwxFromBools(self):
  370. """
  371. L{RWX}'s constructor takes a set of booleans
  372. """
  373. for r in (True, False):
  374. for w in (True, False):
  375. for x in (True, False):
  376. rwx = filepath.RWX(r, w, x)
  377. self.assertEqual(rwx.read, r)
  378. self.assertEqual(rwx.write, w)
  379. self.assertEqual(rwx.execute, x)
  380. rwx = filepath.RWX(True, True, True)
  381. self.assertTrue(rwx.read and rwx.write and rwx.execute)
  382. def test_rwxEqNe(self):
  383. """
  384. L{RWX}'s created with the same booleans are equivalent. If booleans
  385. are different, they are not equal.
  386. """
  387. for r in (True, False):
  388. for w in (True, False):
  389. for x in (True, False):
  390. self.assertEqual(filepath.RWX(r, w, x), filepath.RWX(r, w, x))
  391. self.assertNotUnequal(filepath.RWX(r, w, x), filepath.RWX(r, w, x))
  392. self.assertNotEqual(
  393. filepath.RWX(True, True, True), filepath.RWX(True, True, False)
  394. )
  395. self.assertNotEqual(3, filepath.RWX(True, True, True))
  396. def test_rwxShorthand(self):
  397. """
  398. L{RWX}'s shorthand string should be 'rwx' if read, write, and execute
  399. permission bits are true. If any of those permissions bits are false,
  400. the character is replaced by a '-'.
  401. """
  402. def getChar(val, letter):
  403. if val:
  404. return letter
  405. return "-"
  406. for r in (True, False):
  407. for w in (True, False):
  408. for x in (True, False):
  409. rwx = filepath.RWX(r, w, x)
  410. self.assertEqual(
  411. rwx.shorthand(),
  412. getChar(r, "r") + getChar(w, "w") + getChar(x, "x"),
  413. )
  414. self.assertEqual(filepath.RWX(True, False, True).shorthand(), "r-x")
  415. def test_permissionsFromStat(self):
  416. """
  417. L{Permissions}'s constructor takes a valid permissions bitmask and
  418. parsaes it to produce the correct set of boolean permissions.
  419. """
  420. def _rwxFromStat(statModeInt, who):
  421. def getPermissionBit(what, who):
  422. return (statModeInt & getattr(stat, f"S_I{what}{who}")) > 0
  423. return filepath.RWX(
  424. *(getPermissionBit(what, who) for what in ("R", "W", "X"))
  425. )
  426. for u in range(0, 8):
  427. for g in range(0, 8):
  428. for o in range(0, 8):
  429. chmodString = "%d%d%d" % (u, g, o)
  430. chmodVal = int(chmodString, 8)
  431. perm = filepath.Permissions(chmodVal)
  432. self.assertEqual(
  433. perm.user,
  434. _rwxFromStat(chmodVal, "USR"),
  435. f"{chmodString}: got user: {perm.user}",
  436. )
  437. self.assertEqual(
  438. perm.group,
  439. _rwxFromStat(chmodVal, "GRP"),
  440. f"{chmodString}: got group: {perm.group}",
  441. )
  442. self.assertEqual(
  443. perm.other,
  444. _rwxFromStat(chmodVal, "OTH"),
  445. f"{chmodString}: got other: {perm.other}",
  446. )
  447. perm = filepath.Permissions(0o777)
  448. for who in ("user", "group", "other"):
  449. for what in ("read", "write", "execute"):
  450. self.assertTrue(getattr(getattr(perm, who), what))
  451. def test_permissionsEq(self):
  452. """
  453. Two L{Permissions}'s that are created with the same bitmask
  454. are equivalent
  455. """
  456. self.assertEqual(filepath.Permissions(0o777), filepath.Permissions(0o777))
  457. self.assertNotUnequal(filepath.Permissions(0o777), filepath.Permissions(0o777))
  458. self.assertNotEqual(filepath.Permissions(0o777), filepath.Permissions(0o700))
  459. self.assertNotEqual(3, filepath.Permissions(0o777))
  460. def test_permissionsShorthand(self):
  461. """
  462. L{Permissions}'s shorthand string is the RWX shorthand string for its
  463. user permission bits, group permission bits, and other permission bits
  464. concatenated together, without a space.
  465. """
  466. for u in range(0, 8):
  467. for g in range(0, 8):
  468. for o in range(0, 8):
  469. perm = filepath.Permissions(int("0o%d%d%d" % (u, g, o), 8))
  470. self.assertEqual(
  471. perm.shorthand(),
  472. "".join(
  473. x.shorthand() for x in (perm.user, perm.group, perm.other)
  474. ),
  475. )
  476. self.assertEqual(filepath.Permissions(0o770).shorthand(), "rwxrwx---")
  477. class FilePathTests(AbstractFilePathTests):
  478. """
  479. Test various L{FilePath} path manipulations.
  480. In particular, note that tests defined on this class instead of on the base
  481. class are only run against L{twisted.python.filepath}.
  482. """
  483. def test_chmod(self):
  484. """
  485. L{FilePath.chmod} modifies the permissions of
  486. the passed file as expected (using C{os.stat} to check). We use some
  487. basic modes that should work everywhere (even on Windows).
  488. """
  489. for mode in (0o555, 0o777):
  490. self.path.child(b"sub1").chmod(mode)
  491. self.assertEqual(
  492. stat.S_IMODE(os.stat(self.path.child(b"sub1").path).st_mode), mode
  493. )
  494. def createLinks(self):
  495. """
  496. Create several symbolic links to files and directories.
  497. """
  498. subdir = self.path.child(b"sub1")
  499. os.symlink(subdir.path, self._mkpath(b"sub1.link"))
  500. os.symlink(subdir.child(b"file2").path, self._mkpath(b"file2.link"))
  501. os.symlink(
  502. subdir.child(b"file2").path, self._mkpath(b"sub1", b"sub1.file2.link")
  503. )
  504. @skipIf(symlinkSkip, "Platform does not support symlinks")
  505. def test_realpathSymlink(self):
  506. """
  507. L{FilePath.realpath} returns the path of the ultimate target of a
  508. symlink.
  509. """
  510. self.createLinks()
  511. os.symlink(
  512. self.path.child(b"file2.link").path, self.path.child(b"link.link").path
  513. )
  514. self.assertEqual(
  515. self.path.child(b"link.link").realpath(),
  516. self.path.child(b"sub1").child(b"file2"),
  517. )
  518. @skipIf(symlinkSkip, "Platform does not support symlinks")
  519. def test_realpathCyclicalSymlink(self):
  520. """
  521. L{FilePath.realpath} raises L{filepath.LinkError} if the path is a
  522. symbolic link which is part of a cycle.
  523. """
  524. os.symlink(self.path.child(b"link1").path, self.path.child(b"link2").path)
  525. os.symlink(self.path.child(b"link2").path, self.path.child(b"link1").path)
  526. self.assertRaises(filepath.LinkError, self.path.child(b"link2").realpath)
  527. def test_realpathNoSymlink(self):
  528. """
  529. L{FilePath.realpath} returns the path itself if the path is not a
  530. symbolic link.
  531. """
  532. self.assertEqual(self.path.child(b"sub1").realpath(), self.path.child(b"sub1"))
  533. @skipIf(symlinkSkip, "Platform does not support symlinks")
  534. def test_walkCyclicalSymlink(self):
  535. """
  536. Verify that walking a path with a cyclical symlink raises an error
  537. """
  538. self.createLinks()
  539. os.symlink(
  540. self.path.child(b"sub1").path,
  541. self.path.child(b"sub1").child(b"sub1.loopylink").path,
  542. )
  543. def iterateOverPath():
  544. return [foo.path for foo in self.path.walk()]
  545. self.assertRaises(filepath.LinkError, iterateOverPath)
  546. @skipIf(symlinkSkip, "Platform does not support symlinks")
  547. def test_walkObeysDescendWithCyclicalSymlinks(self):
  548. """
  549. Verify that, after making a path with cyclical symlinks, when the
  550. supplied C{descend} predicate returns C{False}, the target is not
  551. traversed, as if it was a simple symlink.
  552. """
  553. self.createLinks()
  554. # we create cyclical symlinks
  555. os.symlink(
  556. self.path.child(b"sub1").path,
  557. self.path.child(b"sub1").child(b"sub1.loopylink").path,
  558. )
  559. def noSymLinks(path):
  560. return not path.islink()
  561. def iterateOverPath():
  562. return [foo.path for foo in self.path.walk(descend=noSymLinks)]
  563. self.assertTrue(iterateOverPath())
  564. @skipIf(symlinkSkip, "Platform does not support symlinks")
  565. def test_walkObeysDescend(self):
  566. """
  567. Verify that when the supplied C{descend} predicate returns C{False},
  568. the target is not traversed.
  569. """
  570. self.createLinks()
  571. def noSymLinks(path):
  572. return not path.islink()
  573. x = [foo.path for foo in self.path.walk(descend=noSymLinks)]
  574. self.assertEqual(set(x), set(self.all))
  575. def test_getAndSet(self):
  576. content = b"newcontent"
  577. self.path.child(b"new").setContent(content)
  578. newcontent = self.path.child(b"new").getContent()
  579. self.assertEqual(content, newcontent)
  580. content = b"content"
  581. self.path.child(b"new").setContent(content, b".tmp")
  582. newcontent = self.path.child(b"new").getContent()
  583. self.assertEqual(content, newcontent)
  584. def test_getContentFileClosing(self):
  585. """
  586. If reading from the underlying file raises an exception,
  587. L{FilePath.getContent} raises that exception after closing the file.
  588. """
  589. fp = ExplodingFilePath(b"")
  590. self.assertRaises(IOError, fp.getContent)
  591. self.assertTrue(fp.fp.closed)
  592. @skipIf(symlinkSkip, "Platform does not support symlinks")
  593. def test_symbolicLink(self):
  594. """
  595. Verify the behavior of the C{isLink} method against links and
  596. non-links. Also check that the symbolic link shares the directory
  597. property with its target.
  598. """
  599. s4 = self.path.child(b"sub4")
  600. s3 = self.path.child(b"sub3")
  601. os.symlink(s3.path, s4.path)
  602. self.assertTrue(s4.islink())
  603. self.assertFalse(s3.islink())
  604. self.assertTrue(s4.isdir())
  605. self.assertTrue(s3.isdir())
  606. @skipIf(symlinkSkip, "Platform does not support symlinks")
  607. def test_linkTo(self):
  608. """
  609. Verify that symlink creates a valid symlink that is both a link and a
  610. file if its target is a file, or a directory if its target is a
  611. directory.
  612. """
  613. targetLinks = [
  614. (self.path.child(b"sub2"), self.path.child(b"sub2.link")),
  615. (
  616. self.path.child(b"sub2").child(b"file3.ext1"),
  617. self.path.child(b"file3.ext1.link"),
  618. ),
  619. ]
  620. for target, link in targetLinks:
  621. target.linkTo(link)
  622. self.assertTrue(link.islink(), "This is a link")
  623. self.assertEqual(target.isdir(), link.isdir())
  624. self.assertEqual(target.isfile(), link.isfile())
  625. @skipIf(symlinkSkip, "Platform does not support symlinks")
  626. def test_linkToErrors(self):
  627. """
  628. Verify C{linkTo} fails in the following case:
  629. - the target is in a directory that doesn't exist
  630. - the target already exists
  631. """
  632. self.assertRaises(
  633. OSError,
  634. self.path.child(b"file1").linkTo,
  635. self.path.child(b"nosub").child(b"file1"),
  636. )
  637. self.assertRaises(
  638. OSError,
  639. self.path.child(b"file1").linkTo,
  640. self.path.child(b"sub1").child(b"file2"),
  641. )
  642. def testMultiExt(self):
  643. f3 = self.path.child(b"sub3").child(b"file3")
  644. exts = b".foo", b".bar", b"ext1", b"ext2", b"ext3"
  645. self.assertFalse(f3.siblingExtensionSearch(*exts))
  646. f3e = f3.siblingExtension(b".foo")
  647. f3e.touch()
  648. self.assertFalse(not f3.siblingExtensionSearch(*exts).exists())
  649. self.assertFalse(not f3.siblingExtensionSearch(b"*").exists())
  650. f3e.remove()
  651. self.assertFalse(f3.siblingExtensionSearch(*exts))
  652. def testPreauthChild(self):
  653. fp = filepath.FilePath(b".")
  654. fp.preauthChild(b"foo/bar")
  655. self.assertRaises(filepath.InsecurePath, fp.child, "/mon\u20acy")
  656. def testStatCache(self):
  657. p = self.path.child(b"stattest")
  658. p.touch()
  659. self.assertEqual(p.getsize(), 0)
  660. self.assertEqual(abs(p.getmtime() - time.time()) // 20, 0)
  661. self.assertEqual(abs(p.getctime() - time.time()) // 20, 0)
  662. self.assertEqual(abs(p.getatime() - time.time()) // 20, 0)
  663. self.assertTrue(p.exists())
  664. self.assertTrue(p.exists())
  665. # OOB removal: FilePath.remove() will automatically restat
  666. os.remove(p.path)
  667. # test caching
  668. self.assertTrue(p.exists())
  669. p.restat(reraise=False)
  670. self.assertFalse(p.exists())
  671. self.assertFalse(p.islink())
  672. self.assertFalse(p.isdir())
  673. self.assertFalse(p.isfile())
  674. def testPersist(self):
  675. newpath = pickle.loads(pickle.dumps(self.path))
  676. self.assertEqual(self.path.__class__, newpath.__class__)
  677. self.assertEqual(self.path.path, newpath.path)
  678. def testInsecureUNIX(self):
  679. self.assertRaises(filepath.InsecurePath, self.path.child, b"..")
  680. self.assertRaises(filepath.InsecurePath, self.path.child, b"/etc")
  681. self.assertRaises(filepath.InsecurePath, self.path.child, b"../..")
  682. @skipIf(platform.getType() != "win32", "Test will run only on Windows.")
  683. def testInsecureWin32(self):
  684. self.assertRaises(filepath.InsecurePath, self.path.child, b"..\\..")
  685. self.assertRaises(filepath.InsecurePath, self.path.child, b"C:randomfile")
  686. @skipIf(platform.getType() != "win32", "Test will run only on Windows.")
  687. def testInsecureWin32Whacky(self):
  688. """
  689. Windows has 'special' filenames like NUL and CON and COM1 and LPR
  690. and PRN and ... god knows what else. They can be located anywhere in
  691. the filesystem. For obvious reasons, we do not wish to normally permit
  692. access to these.
  693. """
  694. self.assertRaises(filepath.InsecurePath, self.path.child, b"CON")
  695. self.assertRaises(filepath.InsecurePath, self.path.child, b"C:CON")
  696. self.assertRaises(filepath.InsecurePath, self.path.child, r"C:\CON")
  697. def testComparison(self):
  698. self.assertEqual(filepath.FilePath(b"a"), filepath.FilePath(b"a"))
  699. self.assertTrue(filepath.FilePath(b"z") > filepath.FilePath(b"a"))
  700. self.assertTrue(filepath.FilePath(b"z") >= filepath.FilePath(b"a"))
  701. self.assertTrue(filepath.FilePath(b"a") >= filepath.FilePath(b"a"))
  702. self.assertTrue(filepath.FilePath(b"a") <= filepath.FilePath(b"a"))
  703. self.assertTrue(filepath.FilePath(b"a") < filepath.FilePath(b"z"))
  704. self.assertTrue(filepath.FilePath(b"a") <= filepath.FilePath(b"z"))
  705. self.assertTrue(filepath.FilePath(b"a") != filepath.FilePath(b"z"))
  706. self.assertTrue(filepath.FilePath(b"z") != filepath.FilePath(b"a"))
  707. self.assertFalse(filepath.FilePath(b"z") != filepath.FilePath(b"z"))
  708. def test_descendantOnly(self):
  709. """
  710. If C{".."} is in the sequence passed to L{FilePath.descendant},
  711. L{InsecurePath} is raised.
  712. """
  713. self.assertRaises(
  714. filepath.InsecurePath, self.path.descendant, ["mon\u20acy", ".."]
  715. )
  716. def testSibling(self):
  717. p = self.path.child(b"sibling_start")
  718. ts = p.sibling(b"sibling_test")
  719. self.assertEqual(ts.dirname(), p.dirname())
  720. self.assertEqual(ts.basename(), b"sibling_test")
  721. ts.createDirectory()
  722. self.assertIn(ts, self.path.children())
  723. def testTemporarySibling(self):
  724. ts = self.path.temporarySibling()
  725. self.assertEqual(ts.dirname(), self.path.dirname())
  726. self.assertNotIn(ts.basename(), self.path.listdir())
  727. ts.createDirectory()
  728. self.assertIn(ts, self.path.parent().children())
  729. def test_temporarySiblingExtension(self):
  730. """
  731. If L{FilePath.temporarySibling} is given an extension argument, it will
  732. produce path objects with that extension appended to their names.
  733. """
  734. testExtension = b".test-extension"
  735. ts = self.path.temporarySibling(testExtension)
  736. self.assertTrue(
  737. ts.basename().endswith(testExtension),
  738. f"{ts.basename()} does not end with {testExtension}",
  739. )
  740. def test_removeDirectory(self):
  741. """
  742. L{FilePath.remove} on a L{FilePath} that refers to a directory will
  743. recursively delete its contents.
  744. """
  745. self.path.remove()
  746. self.assertFalse(self.path.exists())
  747. @skipIf(symlinkSkip, "Platform does not support symlinks")
  748. def test_removeWithSymlink(self):
  749. """
  750. For a path which is a symbolic link, L{FilePath.remove} just deletes
  751. the link, not the target.
  752. """
  753. link = self.path.child(b"sub1.link")
  754. # setUp creates the sub1 child
  755. os.symlink(self.path.child(b"sub1").path, link.path)
  756. link.remove()
  757. self.assertFalse(link.exists())
  758. self.assertTrue(self.path.child(b"sub1").exists())
  759. def test_copyToDirectory(self):
  760. """
  761. L{FilePath.copyTo} makes a copy of all the contents of the directory
  762. named by that L{FilePath} if it is able to do so.
  763. """
  764. oldPaths = list(self.path.walk()) # Record initial state
  765. fp = filepath.FilePath(self.mktemp())
  766. self.path.copyTo(fp)
  767. self.path.remove()
  768. fp.copyTo(self.path)
  769. newPaths = list(self.path.walk()) # Record double-copy state
  770. newPaths.sort()
  771. oldPaths.sort()
  772. self.assertEqual(newPaths, oldPaths)
  773. def test_copyToMissingDestFileClosing(self):
  774. """
  775. If an exception is raised while L{FilePath.copyTo} is trying to open
  776. source file to read from, the destination file is closed and the
  777. exception is raised to the caller of L{FilePath.copyTo}.
  778. """
  779. nosuch = self.path.child(b"nothere")
  780. # Make it look like something to copy, even though it doesn't exist.
  781. # This could happen if the file is deleted between the isfile check and
  782. # the file actually being opened.
  783. nosuch.isfile = lambda: True
  784. # We won't get as far as writing to this file, but it's still useful for
  785. # tracking whether we closed it.
  786. destination = ExplodingFilePath(self.mktemp())
  787. self.assertRaises(IOError, nosuch.copyTo, destination)
  788. self.assertTrue(destination.fp.closed)
  789. def test_copyToFileClosing(self):
  790. """
  791. If an exception is raised while L{FilePath.copyTo} is copying bytes
  792. between two regular files, the source and destination files are closed
  793. and the exception propagates to the caller of L{FilePath.copyTo}.
  794. """
  795. destination = ExplodingFilePath(self.mktemp())
  796. source = ExplodingFilePath(__file__)
  797. self.assertRaises(IOError, source.copyTo, destination)
  798. self.assertTrue(source.fp.closed)
  799. self.assertTrue(destination.fp.closed)
  800. def test_copyToDirectoryItself(self):
  801. """
  802. L{FilePath.copyTo} fails with an OSError or IOError (depending on
  803. platform, as it propagates errors from open() and write()) when
  804. attempting to copy a directory to a child of itself.
  805. """
  806. self.assertRaises(
  807. (OSError, IOError), self.path.copyTo, self.path.child(b"file1")
  808. )
  809. @skipIf(symlinkSkip, "Platform does not support symlinks")
  810. def test_copyToWithSymlink(self):
  811. """
  812. Verify that copying with followLinks=True copies symlink targets
  813. instead of symlinks
  814. """
  815. os.symlink(self.path.child(b"sub1").path, self.path.child(b"link1").path)
  816. fp = filepath.FilePath(self.mktemp())
  817. self.path.copyTo(fp)
  818. self.assertFalse(fp.child(b"link1").islink())
  819. self.assertEqual(
  820. [x.basename() for x in fp.child(b"sub1").children()],
  821. [x.basename() for x in fp.child(b"link1").children()],
  822. )
  823. @skipIf(symlinkSkip, "Platform does not support symlinks")
  824. def test_copyToWithoutSymlink(self):
  825. """
  826. Verify that copying with followLinks=False copies symlinks as symlinks
  827. """
  828. os.symlink(b"sub1", self.path.child(b"link1").path)
  829. fp = filepath.FilePath(self.mktemp())
  830. self.path.copyTo(fp, followLinks=False)
  831. self.assertTrue(fp.child(b"link1").islink())
  832. self.assertEqual(
  833. os.readlink(self.path.child(b"link1").path),
  834. os.readlink(fp.child(b"link1").path),
  835. )
  836. def test_copyToMissingSource(self):
  837. """
  838. If the source path is missing, L{FilePath.copyTo} raises L{OSError}.
  839. """
  840. path = filepath.FilePath(self.mktemp())
  841. exc = self.assertRaises(OSError, path.copyTo, b"some other path")
  842. self.assertEqual(exc.errno, errno.ENOENT)
  843. def test_moveTo(self):
  844. """
  845. Verify that moving an entire directory results into another directory
  846. with the same content.
  847. """
  848. oldPaths = list(self.path.walk()) # Record initial state
  849. fp = filepath.FilePath(self.mktemp())
  850. self.path.moveTo(fp)
  851. fp.moveTo(self.path)
  852. newPaths = list(self.path.walk()) # Record double-move state
  853. newPaths.sort()
  854. oldPaths.sort()
  855. self.assertEqual(newPaths, oldPaths)
  856. def test_moveToExistsCache(self):
  857. """
  858. A L{FilePath} that has been moved aside with L{FilePath.moveTo} no
  859. longer registers as existing. Its previously non-existent target
  860. exists, though, as it was created by the call to C{moveTo}.
  861. """
  862. fp = filepath.FilePath(self.mktemp())
  863. fp2 = filepath.FilePath(self.mktemp())
  864. fp.touch()
  865. # Both a sanity check (make sure the file status looks right) and an
  866. # enticement for stat-caching logic to kick in and remember that these
  867. # exist / don't exist.
  868. self.assertTrue(fp.exists())
  869. self.assertFalse(fp2.exists())
  870. fp.moveTo(fp2)
  871. self.assertFalse(fp.exists())
  872. self.assertTrue(fp2.exists())
  873. def test_moveToExistsCacheCrossMount(self):
  874. """
  875. The assertion of test_moveToExistsCache should hold in the case of a
  876. cross-mount move.
  877. """
  878. self.setUpFaultyRename()
  879. self.test_moveToExistsCache()
  880. def test_moveToSizeCache(self, hook=lambda: None):
  881. """
  882. L{FilePath.moveTo} clears its destination's status cache, such that
  883. calls to L{FilePath.getsize} after the call to C{moveTo} will report the
  884. new size, not the old one.
  885. This is a separate test from C{test_moveToExistsCache} because it is
  886. intended to cover the fact that the destination's cache is dropped;
  887. test_moveToExistsCache doesn't cover this case because (currently) a
  888. file that doesn't exist yet does not cache the fact of its non-
  889. existence.
  890. """
  891. fp = filepath.FilePath(self.mktemp())
  892. fp2 = filepath.FilePath(self.mktemp())
  893. fp.setContent(b"1234")
  894. fp2.setContent(b"1234567890")
  895. hook()
  896. # Sanity check / kick off caching.
  897. self.assertEqual(fp.getsize(), 4)
  898. self.assertEqual(fp2.getsize(), 10)
  899. # Actually attempting to replace a file on Windows would fail with
  900. # ERROR_ALREADY_EXISTS, but we don't need to test that, just the cached
  901. # metadata, so, delete the file ...
  902. os.remove(fp2.path)
  903. # ... but don't clear the status cache, as fp2.remove() would.
  904. self.assertEqual(fp2.getsize(), 10)
  905. fp.moveTo(fp2)
  906. self.assertEqual(fp2.getsize(), 4)
  907. def test_moveToSizeCacheCrossMount(self):
  908. """
  909. The assertion of test_moveToSizeCache should hold in the case of a
  910. cross-mount move.
  911. """
  912. self.test_moveToSizeCache(hook=self.setUpFaultyRename)
  913. def test_moveToError(self):
  914. """
  915. Verify error behavior of moveTo: it should raises one of OSError or
  916. IOError if you want to move a path into one of its child. It's simply
  917. the error raised by the underlying rename system call.
  918. """
  919. self.assertRaises(
  920. (OSError, IOError), self.path.moveTo, self.path.child(b"file1")
  921. )
  922. def setUpFaultyRename(self):
  923. """
  924. Set up a C{os.rename} that will fail with L{errno.EXDEV} on first call.
  925. This is used to simulate a cross-device rename failure.
  926. @return: a list of pair (src, dest) of calls to C{os.rename}
  927. @rtype: C{list} of C{tuple}
  928. """
  929. invokedWith = []
  930. def faultyRename(src, dest):
  931. invokedWith.append((src, dest))
  932. if len(invokedWith) == 1:
  933. raise OSError(
  934. errno.EXDEV,
  935. "Test-induced failure simulating " "cross-device rename failure",
  936. )
  937. return originalRename(src, dest)
  938. originalRename = os.rename
  939. self.patch(os, "rename", faultyRename)
  940. return invokedWith
  941. def test_crossMountMoveTo(self):
  942. """
  943. C{moveTo} should be able to handle C{EXDEV} error raised by
  944. C{os.rename} when trying to move a file on a different mounted
  945. filesystem.
  946. """
  947. invokedWith = self.setUpFaultyRename()
  948. # Bit of a whitebox test - force os.rename, which moveTo tries
  949. # before falling back to a slower method, to fail, forcing moveTo to
  950. # use the slower behavior.
  951. self.test_moveTo()
  952. # A bit of a sanity check for this whitebox test - if our rename
  953. # was never invoked, the test has probably fallen into disrepair!
  954. self.assertTrue(invokedWith)
  955. @skipIf(symlinkSkip, "Platform does not support symlinks")
  956. def test_crossMountMoveToWithSymlink(self):
  957. """
  958. By default, when moving a symlink, it should follow the link and
  959. actually copy the content of the linked node.
  960. """
  961. invokedWith = self.setUpFaultyRename()
  962. f2 = self.path.child(b"file2")
  963. f3 = self.path.child(b"file3")
  964. os.symlink(self.path.child(b"file1").path, f2.path)
  965. f2.moveTo(f3)
  966. self.assertFalse(f3.islink())
  967. self.assertEqual(f3.getContent(), b"file 1")
  968. self.assertTrue(invokedWith)
  969. @skipIf(symlinkSkip, "Platform does not support symlinks")
  970. def test_crossMountMoveToWithoutSymlink(self):
  971. """
  972. Verify that moveTo called with followLinks=False actually create
  973. another symlink.
  974. """
  975. invokedWith = self.setUpFaultyRename()
  976. f2 = self.path.child(b"file2")
  977. f3 = self.path.child(b"file3")
  978. os.symlink(self.path.child(b"file1").path, f2.path)
  979. f2.moveTo(f3, followLinks=False)
  980. self.assertTrue(f3.islink())
  981. self.assertEqual(f3.getContent(), b"file 1")
  982. self.assertTrue(invokedWith)
  983. def test_createBinaryMode(self):
  984. """
  985. L{FilePath.create} should always open (and write to) files in binary
  986. mode; line-feed octets should be unmodified.
  987. (While this test should pass on all platforms, it is only really
  988. interesting on platforms which have the concept of binary mode, i.e.
  989. Windows platforms.)
  990. """
  991. path = filepath.FilePath(self.mktemp())
  992. with path.create() as f:
  993. self.assertIn("b", f.mode)
  994. f.write(b"\n")
  995. with open(path.path, "rb") as fp:
  996. read = fp.read()
  997. self.assertEqual(read, b"\n")
  998. def testOpen(self):
  999. # Opening a file for reading when it does not already exist is an error
  1000. nonexistent = self.path.child(b"nonexistent")
  1001. e = self.assertRaises(IOError, nonexistent.open)
  1002. self.assertEqual(e.errno, errno.ENOENT)
  1003. # Opening a file for writing when it does not exist is okay
  1004. writer = self.path.child(b"writer")
  1005. with writer.open("w") as f:
  1006. f.write(b"abc\ndef")
  1007. # Make sure those bytes ended up there - and test opening a file for
  1008. # reading when it does exist at the same time
  1009. with writer.open() as f:
  1010. self.assertEqual(f.read(), b"abc\ndef")
  1011. # Re-opening that file in write mode should erase whatever was there.
  1012. writer.open("w").close()
  1013. with writer.open() as f:
  1014. self.assertEqual(f.read(), b"")
  1015. # Put some bytes in a file so we can test that appending does not
  1016. # destroy them.
  1017. appender = self.path.child(b"appender")
  1018. with appender.open("w") as f:
  1019. f.write(b"abc")
  1020. with appender.open("a") as f:
  1021. f.write(b"def")
  1022. with appender.open("r") as f:
  1023. self.assertEqual(f.read(), b"abcdef")
  1024. # read/write should let us do both without erasing those bytes
  1025. with appender.open("r+") as f:
  1026. self.assertEqual(f.read(), b"abcdef")
  1027. # ANSI C *requires* an fseek or an fgetpos between an fread and an
  1028. # fwrite or an fwrite and an fread. We can't reliably get Python to
  1029. # invoke fgetpos, so we seek to a 0 byte offset from the current
  1030. # position instead. Also, Python sucks for making this seek
  1031. # relative to 1 instead of a symbolic constant representing the
  1032. # current file position.
  1033. f.seek(0, 1)
  1034. # Put in some new bytes for us to test for later.
  1035. f.write(b"ghi")
  1036. # Make sure those new bytes really showed up
  1037. with appender.open("r") as f:
  1038. self.assertEqual(f.read(), b"abcdefghi")
  1039. # write/read should let us do both, but erase anything that's there
  1040. # already.
  1041. with appender.open("w+") as f:
  1042. self.assertEqual(f.read(), b"")
  1043. f.seek(0, 1) # Don't forget this!
  1044. f.write(b"123")
  1045. # super append mode should let us read and write and also position the
  1046. # cursor at the end of the file, without erasing everything.
  1047. with appender.open("a+") as f:
  1048. # The order of these lines may seem surprising, but it is
  1049. # necessary. The cursor is not at the end of the file until after
  1050. # the first write.
  1051. f.write(b"456")
  1052. f.seek(0, 1) # Asinine.
  1053. self.assertEqual(f.read(), b"")
  1054. f.seek(0, 0)
  1055. self.assertEqual(f.read(), b"123456")
  1056. # Opening a file exclusively must fail if that file exists already.
  1057. nonexistent.requireCreate(True)
  1058. nonexistent.open("w").close()
  1059. existent = nonexistent
  1060. del nonexistent
  1061. self.assertRaises((OSError, IOError), existent.open)
  1062. def test_openWithExplicitBinaryMode(self):
  1063. """
  1064. Due to a bug in Python 2.7 on Windows including multiple 'b'
  1065. characters in the mode passed to the built-in open() will cause an
  1066. error. FilePath.open() ensures that only a single 'b' character is
  1067. included in the mode passed to the built-in open().
  1068. See http://bugs.python.org/issue7686 for details about the bug.
  1069. """
  1070. writer = self.path.child(b"explicit-binary")
  1071. with writer.open("wb") as file:
  1072. file.write(b"abc\ndef")
  1073. self.assertTrue(writer.exists)
  1074. def test_openWithRedundantExplicitBinaryModes(self):
  1075. """
  1076. Due to a bug in Python 2.7 on Windows including multiple 'b'
  1077. characters in the mode passed to the built-in open() will cause an
  1078. error. No matter how many 'b' modes are specified, FilePath.open()
  1079. ensures that only a single 'b' character is included in the mode
  1080. passed to the built-in open().
  1081. See http://bugs.python.org/issue7686 for details about the bug.
  1082. """
  1083. writer = self.path.child(b"multiple-binary")
  1084. with writer.open("wbb") as file:
  1085. file.write(b"abc\ndef")
  1086. self.assertTrue(writer.exists)
  1087. def test_existsCache(self):
  1088. """
  1089. Check that C{filepath.FilePath.exists} correctly restat the object if
  1090. an operation has occurred in the mean time.
  1091. """
  1092. fp = filepath.FilePath(self.mktemp())
  1093. self.assertFalse(fp.exists())
  1094. fp.makedirs()
  1095. self.assertTrue(fp.exists())
  1096. def test_makedirsMakesDirectoriesRecursively(self):
  1097. """
  1098. C{FilePath.makedirs} creates a directory at C{path}}, including
  1099. recursively creating all parent directories leading up to the path.
  1100. """
  1101. fp = filepath.FilePath(os.path.join(self.mktemp(), b"foo", b"bar", b"baz"))
  1102. self.assertFalse(fp.exists())
  1103. fp.makedirs()
  1104. self.assertTrue(fp.exists())
  1105. self.assertTrue(fp.isdir())
  1106. def test_makedirsMakesDirectoriesWithIgnoreExistingDirectory(self):
  1107. """
  1108. Calling C{FilePath.makedirs} with C{ignoreExistingDirectory} set to
  1109. C{True} has no effect if directory does not exist.
  1110. """
  1111. fp = filepath.FilePath(self.mktemp())
  1112. self.assertFalse(fp.exists())
  1113. fp.makedirs(ignoreExistingDirectory=True)
  1114. self.assertTrue(fp.exists())
  1115. self.assertTrue(fp.isdir())
  1116. def test_makedirsThrowsWithExistentDirectory(self):
  1117. """
  1118. C{FilePath.makedirs} throws an C{OSError} exception
  1119. when called on a directory that already exists.
  1120. """
  1121. fp = filepath.FilePath(os.path.join(self.mktemp()))
  1122. fp.makedirs()
  1123. exception = self.assertRaises(OSError, fp.makedirs)
  1124. self.assertEqual(exception.errno, errno.EEXIST)
  1125. def test_makedirsAcceptsIgnoreExistingDirectory(self):
  1126. """
  1127. C{FilePath.makedirs} succeeds when called on a directory that already
  1128. exists and the c{ignoreExistingDirectory} argument is set to C{True}.
  1129. """
  1130. fp = filepath.FilePath(self.mktemp())
  1131. fp.makedirs()
  1132. self.assertTrue(fp.exists())
  1133. fp.makedirs(ignoreExistingDirectory=True)
  1134. self.assertTrue(fp.exists())
  1135. def test_makedirsIgnoreExistingDirectoryExistAlreadyAFile(self):
  1136. """
  1137. When C{FilePath.makedirs} is called with C{ignoreExistingDirectory} set
  1138. to C{True} it throws an C{OSError} exceptions if path is a file.
  1139. """
  1140. fp = filepath.FilePath(self.mktemp())
  1141. fp.create()
  1142. self.assertTrue(fp.isfile())
  1143. exception = self.assertRaises(
  1144. OSError, fp.makedirs, ignoreExistingDirectory=True
  1145. )
  1146. self.assertEqual(exception.errno, errno.EEXIST)
  1147. def test_makedirsRaisesNonEexistErrorsIgnoreExistingDirectory(self):
  1148. """
  1149. When C{FilePath.makedirs} is called with C{ignoreExistingDirectory} set
  1150. to C{True} it raises an C{OSError} exception if exception errno is not
  1151. EEXIST.
  1152. """
  1153. def faultyMakedirs(path):
  1154. raise OSError(errno.EACCES, "Permission Denied")
  1155. self.patch(os, "makedirs", faultyMakedirs)
  1156. fp = filepath.FilePath(self.mktemp())
  1157. exception = self.assertRaises(
  1158. OSError, fp.makedirs, ignoreExistingDirectory=True
  1159. )
  1160. self.assertEqual(exception.errno, errno.EACCES)
  1161. def test_changed(self):
  1162. """
  1163. L{FilePath.changed} indicates that the L{FilePath} has changed, but does
  1164. not re-read the status information from the filesystem until it is
  1165. queried again via another method, such as C{getsize}.
  1166. """
  1167. fp = filepath.FilePath(self.mktemp())
  1168. fp.setContent(b"12345")
  1169. self.assertEqual(fp.getsize(), 5)
  1170. # Someone else comes along and changes the file.
  1171. with open(fp.path, "wb") as fObj:
  1172. fObj.write(b"12345678")
  1173. # Sanity check for caching: size should still be 5.
  1174. self.assertEqual(fp.getsize(), 5)
  1175. fp.changed()
  1176. # This path should look like we don't know what status it's in, not
  1177. # that we know that it didn't exist when last we checked.
  1178. self.assertEqual(fp.getsize(), 8)
  1179. @skipIf(platform.isWindows(), "Test does not run on Windows")
  1180. def test_getPermissions_POSIX(self):
  1181. """
  1182. Getting permissions for a file returns a L{Permissions} object for
  1183. POSIX platforms (which supports separate user, group, and other
  1184. permissions bits.
  1185. """
  1186. for mode in (0o777, 0o700):
  1187. self.path.child(b"sub1").chmod(mode)
  1188. self.assertEqual(
  1189. self.path.child(b"sub1").getPermissions(), filepath.Permissions(mode)
  1190. )
  1191. self.path.child(b"sub1").chmod(0o764) # sanity check
  1192. self.assertEqual(
  1193. self.path.child(b"sub1").getPermissions().shorthand(), "rwxrw-r--"
  1194. )
  1195. def test_filePathNotDeprecated(self):
  1196. """
  1197. While accessing L{twisted.python.filepath.FilePath.statinfo} is
  1198. deprecated, the filepath itself is not.
  1199. """
  1200. filepath.FilePath(self.mktemp())
  1201. warningInfo = self.flushWarnings([self.test_filePathNotDeprecated])
  1202. self.assertEqual(warningInfo, [])
  1203. @skipIf(not platform.isWindows(), "Test will run only on Windows")
  1204. def test_getPermissions_Windows(self):
  1205. """
  1206. Getting permissions for a file returns a L{Permissions} object in
  1207. Windows. Windows requires a different test, because user permissions
  1208. = group permissions = other permissions. Also, chmod may not be able
  1209. to set the execute bit, so we are skipping tests that set the execute
  1210. bit.
  1211. """
  1212. # Change permission after test so file can be deleted
  1213. self.addCleanup(self.path.child(b"sub1").chmod, 0o777)
  1214. for mode in (0o777, 0o555):
  1215. self.path.child(b"sub1").chmod(mode)
  1216. self.assertEqual(
  1217. self.path.child(b"sub1").getPermissions(), filepath.Permissions(mode)
  1218. )
  1219. self.path.child(b"sub1").chmod(0o511) # sanity check to make sure that
  1220. # user=group=other permissions
  1221. self.assertEqual(
  1222. self.path.child(b"sub1").getPermissions().shorthand(), "r-xr-xr-x"
  1223. )
  1224. def test_whetherBlockOrSocket(self):
  1225. """
  1226. Ensure that a file is not a block or socket
  1227. """
  1228. self.assertFalse(self.path.isBlockDevice())
  1229. self.assertFalse(self.path.isSocket())
  1230. @skipIf(not platform.isWindows(), "Test will run only on Windows")
  1231. def test_statinfoBitsNotImplementedInWindows(self):
  1232. """
  1233. Verify that certain file stats are not available on Windows
  1234. """
  1235. self.assertRaises(NotImplementedError, self.path.getInodeNumber)
  1236. self.assertRaises(NotImplementedError, self.path.getDevice)
  1237. self.assertRaises(NotImplementedError, self.path.getNumberOfHardLinks)
  1238. self.assertRaises(NotImplementedError, self.path.getUserID)
  1239. self.assertRaises(NotImplementedError, self.path.getGroupID)
  1240. @skipIf(platform.isWindows(), "Test does not run on Windows")
  1241. def test_statinfoBitsAreNumbers(self):
  1242. """
  1243. Verify that file inode/device/nlinks/uid/gid stats are numbers in
  1244. a POSIX environment
  1245. """
  1246. c = self.path.child(b"file1")
  1247. for p in self.path, c:
  1248. self.assertIsInstance(p.getInodeNumber(), int)
  1249. self.assertIsInstance(p.getDevice(), int)
  1250. self.assertIsInstance(p.getNumberOfHardLinks(), int)
  1251. self.assertIsInstance(p.getUserID(), int)
  1252. self.assertIsInstance(p.getGroupID(), int)
  1253. self.assertEqual(self.path.getUserID(), c.getUserID())
  1254. self.assertEqual(self.path.getGroupID(), c.getGroupID())
  1255. @skipIf(platform.isWindows(), "Test does not run on Windows")
  1256. def test_statinfoNumbersAreValid(self):
  1257. """
  1258. Verify that the right numbers come back from the right accessor methods
  1259. for file inode/device/nlinks/uid/gid (in a POSIX environment)
  1260. """
  1261. # specify fake statinfo information
  1262. class FakeStat:
  1263. st_ino = 200
  1264. st_dev = 300
  1265. st_nlink = 400
  1266. st_uid = 500
  1267. st_gid = 600
  1268. # monkey patch in a fake restat method for self.path
  1269. fake = FakeStat()
  1270. def fakeRestat(*args, **kwargs):
  1271. self.path._statinfo = fake
  1272. self.path.restat = fakeRestat
  1273. # ensure that restat will need to be called to get values
  1274. self.path._statinfo = None
  1275. self.assertEqual(self.path.getInodeNumber(), fake.st_ino)
  1276. self.assertEqual(self.path.getDevice(), fake.st_dev)
  1277. self.assertEqual(self.path.getNumberOfHardLinks(), fake.st_nlink)
  1278. self.assertEqual(self.path.getUserID(), fake.st_uid)
  1279. self.assertEqual(self.path.getGroupID(), fake.st_gid)
  1280. class SetContentTests(BytesTestCase):
  1281. """
  1282. Tests for L{FilePath.setContent}.
  1283. """
  1284. def test_write(self):
  1285. """
  1286. Contents of the file referred to by a L{FilePath} can be written using
  1287. L{FilePath.setContent}.
  1288. """
  1289. pathString = self.mktemp()
  1290. path = filepath.FilePath(pathString)
  1291. path.setContent(b"hello, world")
  1292. with open(pathString, "rb") as fObj:
  1293. contents = fObj.read()
  1294. self.assertEqual(b"hello, world", contents)
  1295. def test_fileClosing(self):
  1296. """
  1297. If writing to the underlying file raises an exception,
  1298. L{FilePath.setContent} raises that exception after closing the file.
  1299. """
  1300. fp = ExplodingFilePath(b"")
  1301. self.assertRaises(IOError, fp.setContent, b"blah")
  1302. self.assertTrue(fp.fp.closed)
  1303. def test_nameCollision(self):
  1304. """
  1305. L{FilePath.setContent} will use a different temporary filename on each
  1306. invocation, so that multiple processes, threads, or reentrant
  1307. invocations will not collide with each other.
  1308. """
  1309. fp = TrackingFilePath(self.mktemp())
  1310. fp.setContent(b"alpha")
  1311. fp.setContent(b"beta")
  1312. # Sanity check: setContent should only open one derivative path each
  1313. # time to store the temporary file.
  1314. openedSiblings = fp.openedPaths()
  1315. self.assertEqual(len(openedSiblings), 2)
  1316. self.assertNotEqual(openedSiblings[0], openedSiblings[1])
  1317. def _assertOneOpened(self, fp, extension):
  1318. """
  1319. Assert that the L{TrackingFilePath} C{fp} was used to open one sibling
  1320. with the given extension.
  1321. @param fp: A L{TrackingFilePath} which should have been used to open
  1322. file at a sibling path.
  1323. @type fp: L{TrackingFilePath}
  1324. @param extension: The extension the sibling path is expected to have
  1325. had.
  1326. @type extension: L{bytes}
  1327. @raise: C{self.failureException} is raised if the extension of the
  1328. opened file is incorrect or if not exactly one file was opened
  1329. using C{fp}.
  1330. """
  1331. opened = fp.openedPaths()
  1332. self.assertEqual(len(opened), 1, "expected exactly one opened file")
  1333. self.assertTrue(
  1334. opened[0].basename().endswith(extension),
  1335. "{} does not end with {!r} extension".format(
  1336. opened[0].basename(), extension
  1337. ),
  1338. )
  1339. def test_defaultExtension(self):
  1340. """
  1341. L{FilePath.setContent} creates temporary files with the extension
  1342. I{.new} if no alternate extension value is given.
  1343. """
  1344. fp = TrackingFilePath(self.mktemp())
  1345. fp.setContent(b"hello")
  1346. self._assertOneOpened(fp, b".new")
  1347. def test_customExtension(self):
  1348. """
  1349. L{FilePath.setContent} creates temporary files with a user-supplied
  1350. extension so that if it is somehow interrupted while writing them the
  1351. file that it leaves behind will be identifiable.
  1352. """
  1353. fp = TrackingFilePath(self.mktemp())
  1354. fp.setContent(b"goodbye", b"-something-else")
  1355. self._assertOneOpened(fp, b"-something-else")
  1356. class UnicodeFilePathTests(TestCase):
  1357. """
  1358. L{FilePath} instances should have the same internal representation as they
  1359. were instantiated with.
  1360. """
  1361. def test_UnicodeInstantiation(self):
  1362. """
  1363. L{FilePath} instantiated with a text path will return a text-mode
  1364. FilePath.
  1365. """
  1366. fp = filepath.FilePath("./mon\u20acy")
  1367. self.assertEqual(type(fp.path), str)
  1368. def test_UnicodeInstantiationBytesChild(self):
  1369. """
  1370. Calling L{FilePath.child} on a text-mode L{FilePath} with a L{bytes}
  1371. subpath will return a bytes-mode FilePath.
  1372. """
  1373. fp = filepath.FilePath("./parent-mon\u20acy")
  1374. child = fp.child("child-mon\u20acy".encode())
  1375. self.assertEqual(type(child.path), bytes)
  1376. def test_UnicodeInstantiationUnicodeChild(self):
  1377. """
  1378. Calling L{FilePath.child} on a text-mode L{FilePath} with a text
  1379. subpath will return a text-mode FilePath.
  1380. """
  1381. fp = filepath.FilePath("./parent-mon\u20acy")
  1382. child = fp.child("mon\u20acy")
  1383. self.assertEqual(type(child.path), str)
  1384. def test_UnicodeInstantiationUnicodePreauthChild(self):
  1385. """
  1386. Calling L{FilePath.preauthChild} on a text-mode L{FilePath} with a text
  1387. subpath will return a text-mode FilePath.
  1388. """
  1389. fp = filepath.FilePath("./parent-mon\u20acy")
  1390. child = fp.preauthChild("mon\u20acy")
  1391. self.assertEqual(type(child.path), str)
  1392. def test_UnicodeInstantiationBytesPreauthChild(self):
  1393. """
  1394. Calling L{FilePath.preauthChild} on a text-mode L{FilePath} with a bytes
  1395. subpath will return a bytes-mode FilePath.
  1396. """
  1397. fp = filepath.FilePath("./parent-mon\u20acy")
  1398. child = fp.preauthChild("child-mon\u20acy".encode())
  1399. self.assertEqual(type(child.path), bytes)
  1400. def test_BytesInstantiation(self):
  1401. """
  1402. L{FilePath} instantiated with a L{bytes} path will return a bytes-mode
  1403. FilePath.
  1404. """
  1405. fp = filepath.FilePath(b"./")
  1406. self.assertEqual(type(fp.path), bytes)
  1407. def test_BytesInstantiationBytesChild(self):
  1408. """
  1409. Calling L{FilePath.child} on a bytes-mode L{FilePath} with a bytes
  1410. subpath will return a bytes-mode FilePath.
  1411. """
  1412. fp = filepath.FilePath(b"./")
  1413. child = fp.child("child-mon\u20acy".encode())
  1414. self.assertEqual(type(child.path), bytes)
  1415. def test_BytesInstantiationUnicodeChild(self):
  1416. """
  1417. Calling L{FilePath.child} on a bytes-mode L{FilePath} with a text
  1418. subpath will return a text-mode FilePath.
  1419. """
  1420. fp = filepath.FilePath("parent-mon\u20acy".encode())
  1421. child = fp.child("mon\u20acy")
  1422. self.assertEqual(type(child.path), str)
  1423. def test_BytesInstantiationBytesPreauthChild(self):
  1424. """
  1425. Calling L{FilePath.preauthChild} on a bytes-mode L{FilePath} with a
  1426. bytes subpath will return a bytes-mode FilePath.
  1427. """
  1428. fp = filepath.FilePath("./parent-mon\u20acy".encode())
  1429. child = fp.preauthChild("child-mon\u20acy".encode())
  1430. self.assertEqual(type(child.path), bytes)
  1431. def test_BytesInstantiationUnicodePreauthChild(self):
  1432. """
  1433. Calling L{FilePath.preauthChild} on a bytes-mode L{FilePath} with a text
  1434. subpath will return a text-mode FilePath.
  1435. """
  1436. fp = filepath.FilePath("./parent-mon\u20acy".encode())
  1437. child = fp.preauthChild("mon\u20acy")
  1438. self.assertEqual(type(child.path), str)
  1439. @skipIf(platform.isWindows(), "Test will not work on Windows")
  1440. def test_unicoderepr(self):
  1441. """
  1442. The repr of a L{unicode} L{FilePath} shouldn't burst into flames.
  1443. """
  1444. fp = filepath.FilePath("/mon\u20acy")
  1445. reprOutput = repr(fp)
  1446. self.assertEqual("FilePath('/mon\u20acy')", reprOutput)
  1447. @skipIf(platform.isWindows(), "Test will not work on Windows")
  1448. def test_bytesrepr(self):
  1449. """
  1450. The repr of a L{bytes} L{FilePath} shouldn't burst into flames.
  1451. """
  1452. fp = filepath.FilePath("/parent-mon\u20acy".encode())
  1453. reprOutput = repr(fp)
  1454. self.assertEqual("FilePath(b'/parent-mon\\xe2\\x82\\xacy')", reprOutput)
  1455. @skipIf(not platform.isWindows(), "Test only works on Windows")
  1456. def test_unicodereprWindows(self):
  1457. """
  1458. The repr of a L{unicode} L{FilePath} shouldn't burst into flames.
  1459. """
  1460. fp = filepath.FilePath("C:\\")
  1461. reprOutput = repr(fp)
  1462. self.assertEqual("FilePath('C:\\\\')", reprOutput)
  1463. @skipIf(not platform.isWindows(), "Test only works on Windows")
  1464. def test_bytesreprWindows(self):
  1465. """
  1466. The repr of a L{bytes} L{FilePath} shouldn't burst into flames.
  1467. """
  1468. fp = filepath.FilePath(b"C:\\")
  1469. reprOutput = repr(fp)
  1470. self.assertEqual("FilePath(b'C:\\\\')", reprOutput)
  1471. def test_mixedTypeGlobChildren(self):
  1472. """
  1473. C{globChildren} will return the same type as the pattern argument.
  1474. """
  1475. fp = filepath.FilePath("/")
  1476. children = fp.globChildren(b"*")
  1477. self.assertIsInstance(children[0].path, bytes)
  1478. def test_unicodeGlobChildren(self):
  1479. """
  1480. C{globChildren} works with L{unicode}.
  1481. """
  1482. fp = filepath.FilePath("/")
  1483. children = fp.globChildren("*")
  1484. self.assertIsInstance(children[0].path, str)
  1485. def test_unicodeBasename(self):
  1486. """
  1487. Calling C{basename} on an text- L{FilePath} returns L{unicode}.
  1488. """
  1489. fp = filepath.FilePath("./")
  1490. self.assertIsInstance(fp.basename(), str)
  1491. def test_unicodeDirname(self):
  1492. """
  1493. Calling C{dirname} on a text-mode L{FilePath} returns L{unicode}.
  1494. """
  1495. fp = filepath.FilePath("./")
  1496. self.assertIsInstance(fp.dirname(), str)
  1497. def test_unicodeParent(self):
  1498. """
  1499. Calling C{parent} on a text-mode L{FilePath} will return a text-mode
  1500. L{FilePath}.
  1501. """
  1502. fp = filepath.FilePath("./")
  1503. parent = fp.parent()
  1504. self.assertIsInstance(parent.path, str)
  1505. def test_mixedTypeTemporarySibling(self):
  1506. """
  1507. A L{bytes} extension to C{temporarySibling} will mean a L{bytes} mode
  1508. L{FilePath} is returned.
  1509. """
  1510. fp = filepath.FilePath("./mon\u20acy")
  1511. tempSibling = fp.temporarySibling(b".txt")
  1512. self.assertIsInstance(tempSibling.path, bytes)
  1513. def test_unicodeTemporarySibling(self):
  1514. """
  1515. A L{unicode} extension to C{temporarySibling} will mean a L{unicode}
  1516. mode L{FilePath} is returned.
  1517. """
  1518. fp = filepath.FilePath("/tmp/mon\u20acy")
  1519. tempSibling = fp.temporarySibling(".txt")
  1520. self.assertIsInstance(tempSibling.path, str)
  1521. def test_mixedTypeSiblingExtensionSearch(self):
  1522. """
  1523. C{siblingExtensionSearch} called with L{bytes} on a L{unicode}-mode
  1524. L{FilePath} will return a L{list} of L{bytes}-mode L{FilePath}s.
  1525. """
  1526. fp = filepath.FilePath("./mon\u20acy")
  1527. sibling = filepath.FilePath(fp._asTextPath() + ".txt")
  1528. sibling.touch()
  1529. newPath = fp.siblingExtensionSearch(b".txt")
  1530. self.assertIsInstance(newPath, filepath.FilePath)
  1531. self.assertIsInstance(newPath.path, bytes)
  1532. def test_unicodeSiblingExtensionSearch(self):
  1533. """
  1534. C{siblingExtensionSearch} called with L{unicode} on a L{unicode}-mode
  1535. L{FilePath} will return a L{list} of L{unicode}-mode L{FilePath}s.
  1536. """
  1537. fp = filepath.FilePath("./mon\u20acy")
  1538. sibling = filepath.FilePath(fp._asTextPath() + ".txt")
  1539. sibling.touch()
  1540. newPath = fp.siblingExtensionSearch(".txt")
  1541. self.assertIsInstance(newPath, filepath.FilePath)
  1542. self.assertIsInstance(newPath.path, str)
  1543. def test_mixedTypeSiblingExtension(self):
  1544. """
  1545. C{siblingExtension} called with L{bytes} on a L{unicode}-mode
  1546. L{FilePath} will return a L{bytes}-mode L{FilePath}.
  1547. """
  1548. fp = filepath.FilePath("./mon\u20acy")
  1549. sibling = filepath.FilePath(fp._asTextPath() + ".txt")
  1550. sibling.touch()
  1551. newPath = fp.siblingExtension(b".txt")
  1552. self.assertIsInstance(newPath, filepath.FilePath)
  1553. self.assertIsInstance(newPath.path, bytes)
  1554. def test_unicodeSiblingExtension(self):
  1555. """
  1556. C{siblingExtension} called with L{unicode} on a L{unicode}-mode
  1557. L{FilePath} will return a L{unicode}-mode L{FilePath}.
  1558. """
  1559. fp = filepath.FilePath("./mon\u20acy")
  1560. sibling = filepath.FilePath(fp._asTextPath() + ".txt")
  1561. sibling.touch()
  1562. newPath = fp.siblingExtension(".txt")
  1563. self.assertIsInstance(newPath, filepath.FilePath)
  1564. self.assertIsInstance(newPath.path, str)
  1565. def test_mixedTypeChildSearchPreauth(self):
  1566. """
  1567. C{childSearchPreauth} called with L{bytes} on a L{unicode}-mode
  1568. L{FilePath} will return a L{bytes}-mode L{FilePath}.
  1569. """
  1570. fp = filepath.FilePath("./mon\u20acy")
  1571. fp.createDirectory()
  1572. self.addCleanup(lambda: fp.remove())
  1573. child = fp.child("text.txt")
  1574. child.touch()
  1575. newPath = fp.childSearchPreauth(b"text.txt")
  1576. self.assertIsInstance(newPath, filepath.FilePath)
  1577. self.assertIsInstance(newPath.path, bytes)
  1578. def test_unicodeChildSearchPreauth(self):
  1579. """
  1580. C{childSearchPreauth} called with L{unicode} on a L{unicode}-mode
  1581. L{FilePath} will return a L{unicode}-mode L{FilePath}.
  1582. """
  1583. fp = filepath.FilePath("./mon\u20acy")
  1584. fp.createDirectory()
  1585. self.addCleanup(lambda: fp.remove())
  1586. child = fp.child("text.txt")
  1587. child.touch()
  1588. newPath = fp.childSearchPreauth("text.txt")
  1589. self.assertIsInstance(newPath, filepath.FilePath)
  1590. self.assertIsInstance(newPath.path, str)
  1591. def test_asBytesModeFromUnicode(self):
  1592. """
  1593. C{asBytesMode} on a L{unicode}-mode L{FilePath} returns a new
  1594. L{bytes}-mode L{FilePath}.
  1595. """
  1596. fp = filepath.FilePath("./tmp")
  1597. newfp = fp.asBytesMode()
  1598. self.assertIsNot(fp, newfp)
  1599. self.assertIsInstance(newfp.path, bytes)
  1600. def test_asTextModeFromBytes(self):
  1601. """
  1602. C{asBytesMode} on a L{unicode}-mode L{FilePath} returns a new
  1603. L{bytes}-mode L{FilePath}.
  1604. """
  1605. fp = filepath.FilePath(b"./tmp")
  1606. newfp = fp.asTextMode()
  1607. self.assertIsNot(fp, newfp)
  1608. self.assertIsInstance(newfp.path, str)
  1609. def test_asBytesModeFromBytes(self):
  1610. """
  1611. C{asBytesMode} on a L{bytes}-mode L{FilePath} returns the same
  1612. L{bytes}-mode L{FilePath}.
  1613. """
  1614. fp = filepath.FilePath(b"./tmp")
  1615. newfp = fp.asBytesMode()
  1616. self.assertIs(fp, newfp)
  1617. self.assertIsInstance(newfp.path, bytes)
  1618. def test_asTextModeFromUnicode(self):
  1619. """
  1620. C{asTextMode} on a L{unicode}-mode L{FilePath} returns the same
  1621. L{unicode}-mode L{FilePath}.
  1622. """
  1623. fp = filepath.FilePath("./tmp")
  1624. newfp = fp.asTextMode()
  1625. self.assertIs(fp, newfp)
  1626. self.assertIsInstance(newfp.path, str)
  1627. def test_asBytesModeFromUnicodeWithEncoding(self):
  1628. """
  1629. C{asBytesMode} with an C{encoding} argument uses that encoding when
  1630. coercing the L{unicode}-mode L{FilePath} to a L{bytes}-mode L{FilePath}.
  1631. """
  1632. fp = filepath.FilePath("\u2603")
  1633. newfp = fp.asBytesMode(encoding="utf-8")
  1634. self.assertIn(b"\xe2\x98\x83", newfp.path)
  1635. def test_asTextModeFromBytesWithEncoding(self):
  1636. """
  1637. C{asTextMode} with an C{encoding} argument uses that encoding when
  1638. coercing the L{bytes}-mode L{FilePath} to a L{unicode}-mode L{FilePath}.
  1639. """
  1640. fp = filepath.FilePath(b"\xe2\x98\x83")
  1641. newfp = fp.asTextMode(encoding="utf-8")
  1642. self.assertIn("\u2603", newfp.path)
  1643. def test_asBytesModeFromUnicodeWithUnusableEncoding(self):
  1644. """
  1645. C{asBytesMode} with an C{encoding} argument that can't be used to encode
  1646. the unicode path raises a L{UnicodeError}.
  1647. """
  1648. fp = filepath.FilePath("\u2603")
  1649. with self.assertRaises(UnicodeError):
  1650. fp.asBytesMode(encoding="ascii")
  1651. def test_asTextModeFromBytesWithUnusableEncoding(self):
  1652. """
  1653. C{asTextMode} with an C{encoding} argument that can't be used to encode
  1654. the unicode path raises a L{UnicodeError}.
  1655. """
  1656. fp = filepath.FilePath(br"\u2603")
  1657. with self.assertRaises(UnicodeError):
  1658. fp.asTextMode(encoding="utf-32")