test_os.py 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548
  1. # As a test suite for the os module, this is woefully inadequate, but this
  2. # does add tests for a few functions which have been determined to be more
  3. # portable than they had been thought to be.
  4. import asyncio
  5. import codecs
  6. import contextlib
  7. import decimal
  8. import errno
  9. import fnmatch
  10. import fractions
  11. import itertools
  12. import locale
  13. import os
  14. import pickle
  15. import select
  16. import shutil
  17. import signal
  18. import socket
  19. import stat
  20. import struct
  21. import subprocess
  22. import sys
  23. import sysconfig
  24. import tempfile
  25. import textwrap
  26. import time
  27. import types
  28. import unittest
  29. import uuid
  30. import warnings
  31. from test import support
  32. from test.support import import_helper
  33. from test.support import os_helper
  34. from test.support import socket_helper
  35. from test.support import warnings_helper
  36. from platform import win32_is_iot
  37. try:
  38. import resource
  39. except ImportError:
  40. resource = None
  41. try:
  42. import fcntl
  43. except ImportError:
  44. fcntl = None
  45. try:
  46. import _winapi
  47. except ImportError:
  48. _winapi = None
  49. try:
  50. import pwd
  51. all_users = [u.pw_uid for u in pwd.getpwall()]
  52. except (ImportError, AttributeError):
  53. all_users = []
  54. try:
  55. from _testcapi import INT_MAX, PY_SSIZE_T_MAX
  56. except ImportError:
  57. INT_MAX = PY_SSIZE_T_MAX = sys.maxsize
  58. try:
  59. import mmap
  60. except ImportError:
  61. mmap = None
  62. from test.support.script_helper import assert_python_ok
  63. from test.support import unix_shell
  64. from test.support.os_helper import FakePath
  65. root_in_posix = False
  66. if hasattr(os, 'geteuid'):
  67. root_in_posix = (os.geteuid() == 0)
  68. # Detect whether we're on a Linux system that uses the (now outdated
  69. # and unmaintained) linuxthreads threading library. There's an issue
  70. # when combining linuxthreads with a failed execv call: see
  71. # http://bugs.python.org/issue4970.
  72. if hasattr(sys, 'thread_info') and sys.thread_info.version:
  73. USING_LINUXTHREADS = sys.thread_info.version.startswith("linuxthreads")
  74. else:
  75. USING_LINUXTHREADS = False
  76. # Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
  77. HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
  78. def requires_os_func(name):
  79. return unittest.skipUnless(hasattr(os, name), 'requires os.%s' % name)
  80. def create_file(filename, content=b'content'):
  81. with open(filename, "xb", 0) as fp:
  82. fp.write(content)
  83. # bpo-41625: On AIX, splice() only works with a socket, not with a pipe.
  84. requires_splice_pipe = unittest.skipIf(sys.platform.startswith("aix"),
  85. 'on AIX, splice() only accepts sockets')
  86. def tearDownModule():
  87. asyncio.set_event_loop_policy(None)
  88. class MiscTests(unittest.TestCase):
  89. def test_getcwd(self):
  90. cwd = os.getcwd()
  91. self.assertIsInstance(cwd, str)
  92. def test_getcwd_long_path(self):
  93. # bpo-37412: On Linux, PATH_MAX is usually around 4096 bytes. On
  94. # Windows, MAX_PATH is defined as 260 characters, but Windows supports
  95. # longer path if longer paths support is enabled. Internally, the os
  96. # module uses MAXPATHLEN which is at least 1024.
  97. #
  98. # Use a directory name of 200 characters to fit into Windows MAX_PATH
  99. # limit.
  100. #
  101. # On Windows, the test can stop when trying to create a path longer
  102. # than MAX_PATH if long paths support is disabled:
  103. # see RtlAreLongPathsEnabled().
  104. min_len = 2000 # characters
  105. # On VxWorks, PATH_MAX is defined as 1024 bytes. Creating a path
  106. # longer than PATH_MAX will fail.
  107. if sys.platform == 'vxworks':
  108. min_len = 1000
  109. dirlen = 200 # characters
  110. dirname = 'python_test_dir_'
  111. dirname = dirname + ('a' * (dirlen - len(dirname)))
  112. with tempfile.TemporaryDirectory() as tmpdir:
  113. with os_helper.change_cwd(tmpdir) as path:
  114. expected = path
  115. while True:
  116. cwd = os.getcwd()
  117. self.assertEqual(cwd, expected)
  118. need = min_len - (len(cwd) + len(os.path.sep))
  119. if need <= 0:
  120. break
  121. if len(dirname) > need and need > 0:
  122. dirname = dirname[:need]
  123. path = os.path.join(path, dirname)
  124. try:
  125. os.mkdir(path)
  126. # On Windows, chdir() can fail
  127. # even if mkdir() succeeded
  128. os.chdir(path)
  129. except FileNotFoundError:
  130. # On Windows, catch ERROR_PATH_NOT_FOUND (3) and
  131. # ERROR_FILENAME_EXCED_RANGE (206) errors
  132. # ("The filename or extension is too long")
  133. break
  134. except OSError as exc:
  135. if exc.errno == errno.ENAMETOOLONG:
  136. break
  137. else:
  138. raise
  139. expected = path
  140. if support.verbose:
  141. print(f"Tested current directory length: {len(cwd)}")
  142. def test_getcwdb(self):
  143. cwd = os.getcwdb()
  144. self.assertIsInstance(cwd, bytes)
  145. self.assertEqual(os.fsdecode(cwd), os.getcwd())
  146. # Tests creating TESTFN
  147. class FileTests(unittest.TestCase):
  148. def setUp(self):
  149. if os.path.lexists(os_helper.TESTFN):
  150. os.unlink(os_helper.TESTFN)
  151. tearDown = setUp
  152. def test_access(self):
  153. f = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
  154. os.close(f)
  155. self.assertTrue(os.access(os_helper.TESTFN, os.W_OK))
  156. @unittest.skipIf(
  157. support.is_emscripten, "Test is unstable under Emscripten."
  158. )
  159. @unittest.skipIf(
  160. support.is_wasi, "WASI does not support dup."
  161. )
  162. def test_closerange(self):
  163. first = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
  164. # We must allocate two consecutive file descriptors, otherwise
  165. # it will mess up other file descriptors (perhaps even the three
  166. # standard ones).
  167. second = os.dup(first)
  168. try:
  169. retries = 0
  170. while second != first + 1:
  171. os.close(first)
  172. retries += 1
  173. if retries > 10:
  174. # XXX test skipped
  175. self.skipTest("couldn't allocate two consecutive fds")
  176. first, second = second, os.dup(second)
  177. finally:
  178. os.close(second)
  179. # close a fd that is open, and one that isn't
  180. os.closerange(first, first + 2)
  181. self.assertRaises(OSError, os.write, first, b"a")
  182. @support.cpython_only
  183. def test_rename(self):
  184. path = os_helper.TESTFN
  185. old = sys.getrefcount(path)
  186. self.assertRaises(TypeError, os.rename, path, 0)
  187. new = sys.getrefcount(path)
  188. self.assertEqual(old, new)
  189. def test_read(self):
  190. with open(os_helper.TESTFN, "w+b") as fobj:
  191. fobj.write(b"spam")
  192. fobj.flush()
  193. fd = fobj.fileno()
  194. os.lseek(fd, 0, 0)
  195. s = os.read(fd, 4)
  196. self.assertEqual(type(s), bytes)
  197. self.assertEqual(s, b"spam")
  198. @support.cpython_only
  199. # Skip the test on 32-bit platforms: the number of bytes must fit in a
  200. # Py_ssize_t type
  201. @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX,
  202. "needs INT_MAX < PY_SSIZE_T_MAX")
  203. @support.bigmemtest(size=INT_MAX + 10, memuse=1, dry_run=False)
  204. def test_large_read(self, size):
  205. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  206. create_file(os_helper.TESTFN, b'test')
  207. # Issue #21932: Make sure that os.read() does not raise an
  208. # OverflowError for size larger than INT_MAX
  209. with open(os_helper.TESTFN, "rb") as fp:
  210. data = os.read(fp.fileno(), size)
  211. # The test does not try to read more than 2 GiB at once because the
  212. # operating system is free to return less bytes than requested.
  213. self.assertEqual(data, b'test')
  214. def test_write(self):
  215. # os.write() accepts bytes- and buffer-like objects but not strings
  216. fd = os.open(os_helper.TESTFN, os.O_CREAT | os.O_WRONLY)
  217. self.assertRaises(TypeError, os.write, fd, "beans")
  218. os.write(fd, b"bacon\n")
  219. os.write(fd, bytearray(b"eggs\n"))
  220. os.write(fd, memoryview(b"spam\n"))
  221. os.close(fd)
  222. with open(os_helper.TESTFN, "rb") as fobj:
  223. self.assertEqual(fobj.read().splitlines(),
  224. [b"bacon", b"eggs", b"spam"])
  225. def write_windows_console(self, *args):
  226. retcode = subprocess.call(args,
  227. # use a new console to not flood the test output
  228. creationflags=subprocess.CREATE_NEW_CONSOLE,
  229. # use a shell to hide the console window (SW_HIDE)
  230. shell=True)
  231. self.assertEqual(retcode, 0)
  232. @unittest.skipUnless(sys.platform == 'win32',
  233. 'test specific to the Windows console')
  234. def test_write_windows_console(self):
  235. # Issue #11395: the Windows console returns an error (12: not enough
  236. # space error) on writing into stdout if stdout mode is binary and the
  237. # length is greater than 66,000 bytes (or less, depending on heap
  238. # usage).
  239. code = "print('x' * 100000)"
  240. self.write_windows_console(sys.executable, "-c", code)
  241. self.write_windows_console(sys.executable, "-u", "-c", code)
  242. def fdopen_helper(self, *args):
  243. fd = os.open(os_helper.TESTFN, os.O_RDONLY)
  244. f = os.fdopen(fd, *args, encoding="utf-8")
  245. f.close()
  246. def test_fdopen(self):
  247. fd = os.open(os_helper.TESTFN, os.O_CREAT|os.O_RDWR)
  248. os.close(fd)
  249. self.fdopen_helper()
  250. self.fdopen_helper('r')
  251. self.fdopen_helper('r', 100)
  252. def test_replace(self):
  253. TESTFN2 = os_helper.TESTFN + ".2"
  254. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  255. self.addCleanup(os_helper.unlink, TESTFN2)
  256. create_file(os_helper.TESTFN, b"1")
  257. create_file(TESTFN2, b"2")
  258. os.replace(os_helper.TESTFN, TESTFN2)
  259. self.assertRaises(FileNotFoundError, os.stat, os_helper.TESTFN)
  260. with open(TESTFN2, 'r', encoding='utf-8') as f:
  261. self.assertEqual(f.read(), "1")
  262. def test_open_keywords(self):
  263. f = os.open(path=__file__, flags=os.O_RDONLY, mode=0o777,
  264. dir_fd=None)
  265. os.close(f)
  266. def test_symlink_keywords(self):
  267. symlink = support.get_attribute(os, "symlink")
  268. try:
  269. symlink(src='target', dst=os_helper.TESTFN,
  270. target_is_directory=False, dir_fd=None)
  271. except (NotImplementedError, OSError):
  272. pass # No OS support or unprivileged user
  273. @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
  274. def test_copy_file_range_invalid_values(self):
  275. with self.assertRaises(ValueError):
  276. os.copy_file_range(0, 1, -10)
  277. @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
  278. def test_copy_file_range(self):
  279. TESTFN2 = os_helper.TESTFN + ".3"
  280. data = b'0123456789'
  281. create_file(os_helper.TESTFN, data)
  282. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  283. in_file = open(os_helper.TESTFN, 'rb')
  284. self.addCleanup(in_file.close)
  285. in_fd = in_file.fileno()
  286. out_file = open(TESTFN2, 'w+b')
  287. self.addCleanup(os_helper.unlink, TESTFN2)
  288. self.addCleanup(out_file.close)
  289. out_fd = out_file.fileno()
  290. try:
  291. i = os.copy_file_range(in_fd, out_fd, 5)
  292. except OSError as e:
  293. # Handle the case in which Python was compiled
  294. # in a system with the syscall but without support
  295. # in the kernel.
  296. if e.errno != errno.ENOSYS:
  297. raise
  298. self.skipTest(e)
  299. else:
  300. # The number of copied bytes can be less than
  301. # the number of bytes originally requested.
  302. self.assertIn(i, range(0, 6));
  303. with open(TESTFN2, 'rb') as in_file:
  304. self.assertEqual(in_file.read(), data[:i])
  305. @unittest.skipUnless(hasattr(os, 'copy_file_range'), 'test needs os.copy_file_range()')
  306. def test_copy_file_range_offset(self):
  307. TESTFN4 = os_helper.TESTFN + ".4"
  308. data = b'0123456789'
  309. bytes_to_copy = 6
  310. in_skip = 3
  311. out_seek = 5
  312. create_file(os_helper.TESTFN, data)
  313. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  314. in_file = open(os_helper.TESTFN, 'rb')
  315. self.addCleanup(in_file.close)
  316. in_fd = in_file.fileno()
  317. out_file = open(TESTFN4, 'w+b')
  318. self.addCleanup(os_helper.unlink, TESTFN4)
  319. self.addCleanup(out_file.close)
  320. out_fd = out_file.fileno()
  321. try:
  322. i = os.copy_file_range(in_fd, out_fd, bytes_to_copy,
  323. offset_src=in_skip,
  324. offset_dst=out_seek)
  325. except OSError as e:
  326. # Handle the case in which Python was compiled
  327. # in a system with the syscall but without support
  328. # in the kernel.
  329. if e.errno != errno.ENOSYS:
  330. raise
  331. self.skipTest(e)
  332. else:
  333. # The number of copied bytes can be less than
  334. # the number of bytes originally requested.
  335. self.assertIn(i, range(0, bytes_to_copy+1));
  336. with open(TESTFN4, 'rb') as in_file:
  337. read = in_file.read()
  338. # seeked bytes (5) are zero'ed
  339. self.assertEqual(read[:out_seek], b'\x00'*out_seek)
  340. # 012 are skipped (in_skip)
  341. # 345678 are copied in the file (in_skip + bytes_to_copy)
  342. self.assertEqual(read[out_seek:],
  343. data[in_skip:in_skip+i])
  344. @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
  345. def test_splice_invalid_values(self):
  346. with self.assertRaises(ValueError):
  347. os.splice(0, 1, -10)
  348. @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
  349. @requires_splice_pipe
  350. def test_splice(self):
  351. TESTFN2 = os_helper.TESTFN + ".3"
  352. data = b'0123456789'
  353. create_file(os_helper.TESTFN, data)
  354. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  355. in_file = open(os_helper.TESTFN, 'rb')
  356. self.addCleanup(in_file.close)
  357. in_fd = in_file.fileno()
  358. read_fd, write_fd = os.pipe()
  359. self.addCleanup(lambda: os.close(read_fd))
  360. self.addCleanup(lambda: os.close(write_fd))
  361. try:
  362. i = os.splice(in_fd, write_fd, 5)
  363. except OSError as e:
  364. # Handle the case in which Python was compiled
  365. # in a system with the syscall but without support
  366. # in the kernel.
  367. if e.errno != errno.ENOSYS:
  368. raise
  369. self.skipTest(e)
  370. else:
  371. # The number of copied bytes can be less than
  372. # the number of bytes originally requested.
  373. self.assertIn(i, range(0, 6));
  374. self.assertEqual(os.read(read_fd, 100), data[:i])
  375. @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
  376. @requires_splice_pipe
  377. def test_splice_offset_in(self):
  378. TESTFN4 = os_helper.TESTFN + ".4"
  379. data = b'0123456789'
  380. bytes_to_copy = 6
  381. in_skip = 3
  382. create_file(os_helper.TESTFN, data)
  383. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  384. in_file = open(os_helper.TESTFN, 'rb')
  385. self.addCleanup(in_file.close)
  386. in_fd = in_file.fileno()
  387. read_fd, write_fd = os.pipe()
  388. self.addCleanup(lambda: os.close(read_fd))
  389. self.addCleanup(lambda: os.close(write_fd))
  390. try:
  391. i = os.splice(in_fd, write_fd, bytes_to_copy, offset_src=in_skip)
  392. except OSError as e:
  393. # Handle the case in which Python was compiled
  394. # in a system with the syscall but without support
  395. # in the kernel.
  396. if e.errno != errno.ENOSYS:
  397. raise
  398. self.skipTest(e)
  399. else:
  400. # The number of copied bytes can be less than
  401. # the number of bytes originally requested.
  402. self.assertIn(i, range(0, bytes_to_copy+1));
  403. read = os.read(read_fd, 100)
  404. # 012 are skipped (in_skip)
  405. # 345678 are copied in the file (in_skip + bytes_to_copy)
  406. self.assertEqual(read, data[in_skip:in_skip+i])
  407. @unittest.skipUnless(hasattr(os, 'splice'), 'test needs os.splice()')
  408. @requires_splice_pipe
  409. def test_splice_offset_out(self):
  410. TESTFN4 = os_helper.TESTFN + ".4"
  411. data = b'0123456789'
  412. bytes_to_copy = 6
  413. out_seek = 3
  414. create_file(os_helper.TESTFN, data)
  415. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  416. read_fd, write_fd = os.pipe()
  417. self.addCleanup(lambda: os.close(read_fd))
  418. self.addCleanup(lambda: os.close(write_fd))
  419. os.write(write_fd, data)
  420. out_file = open(TESTFN4, 'w+b')
  421. self.addCleanup(os_helper.unlink, TESTFN4)
  422. self.addCleanup(out_file.close)
  423. out_fd = out_file.fileno()
  424. try:
  425. i = os.splice(read_fd, out_fd, bytes_to_copy, offset_dst=out_seek)
  426. except OSError as e:
  427. # Handle the case in which Python was compiled
  428. # in a system with the syscall but without support
  429. # in the kernel.
  430. if e.errno != errno.ENOSYS:
  431. raise
  432. self.skipTest(e)
  433. else:
  434. # The number of copied bytes can be less than
  435. # the number of bytes originally requested.
  436. self.assertIn(i, range(0, bytes_to_copy+1));
  437. with open(TESTFN4, 'rb') as in_file:
  438. read = in_file.read()
  439. # seeked bytes (5) are zero'ed
  440. self.assertEqual(read[:out_seek], b'\x00'*out_seek)
  441. # 012 are skipped (in_skip)
  442. # 345678 are copied in the file (in_skip + bytes_to_copy)
  443. self.assertEqual(read[out_seek:], data[:i])
  444. # Test attributes on return values from os.*stat* family.
  445. class StatAttributeTests(unittest.TestCase):
  446. def setUp(self):
  447. self.fname = os_helper.TESTFN
  448. self.addCleanup(os_helper.unlink, self.fname)
  449. create_file(self.fname, b"ABC")
  450. def check_stat_attributes(self, fname):
  451. result = os.stat(fname)
  452. # Make sure direct access works
  453. self.assertEqual(result[stat.ST_SIZE], 3)
  454. self.assertEqual(result.st_size, 3)
  455. # Make sure all the attributes are there
  456. members = dir(result)
  457. for name in dir(stat):
  458. if name[:3] == 'ST_':
  459. attr = name.lower()
  460. if name.endswith("TIME"):
  461. def trunc(x): return int(x)
  462. else:
  463. def trunc(x): return x
  464. self.assertEqual(trunc(getattr(result, attr)),
  465. result[getattr(stat, name)])
  466. self.assertIn(attr, members)
  467. # Make sure that the st_?time and st_?time_ns fields roughly agree
  468. # (they should always agree up to around tens-of-microseconds)
  469. for name in 'st_atime st_mtime st_ctime'.split():
  470. floaty = int(getattr(result, name) * 100000)
  471. nanosecondy = getattr(result, name + "_ns") // 10000
  472. self.assertAlmostEqual(floaty, nanosecondy, delta=2)
  473. try:
  474. result[200]
  475. self.fail("No exception raised")
  476. except IndexError:
  477. pass
  478. # Make sure that assignment fails
  479. try:
  480. result.st_mode = 1
  481. self.fail("No exception raised")
  482. except AttributeError:
  483. pass
  484. try:
  485. result.st_rdev = 1
  486. self.fail("No exception raised")
  487. except (AttributeError, TypeError):
  488. pass
  489. try:
  490. result.parrot = 1
  491. self.fail("No exception raised")
  492. except AttributeError:
  493. pass
  494. # Use the stat_result constructor with a too-short tuple.
  495. try:
  496. result2 = os.stat_result((10,))
  497. self.fail("No exception raised")
  498. except TypeError:
  499. pass
  500. # Use the constructor with a too-long tuple.
  501. try:
  502. result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
  503. except TypeError:
  504. pass
  505. def test_stat_attributes(self):
  506. self.check_stat_attributes(self.fname)
  507. def test_stat_attributes_bytes(self):
  508. try:
  509. fname = self.fname.encode(sys.getfilesystemencoding())
  510. except UnicodeEncodeError:
  511. self.skipTest("cannot encode %a for the filesystem" % self.fname)
  512. self.check_stat_attributes(fname)
  513. def test_stat_result_pickle(self):
  514. result = os.stat(self.fname)
  515. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  516. p = pickle.dumps(result, proto)
  517. self.assertIn(b'stat_result', p)
  518. if proto < 4:
  519. self.assertIn(b'cos\nstat_result\n', p)
  520. unpickled = pickle.loads(p)
  521. self.assertEqual(result, unpickled)
  522. @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()')
  523. def test_statvfs_attributes(self):
  524. result = os.statvfs(self.fname)
  525. # Make sure direct access works
  526. self.assertEqual(result.f_bfree, result[3])
  527. # Make sure all the attributes are there.
  528. members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
  529. 'ffree', 'favail', 'flag', 'namemax')
  530. for value, member in enumerate(members):
  531. self.assertEqual(getattr(result, 'f_' + member), result[value])
  532. self.assertTrue(isinstance(result.f_fsid, int))
  533. # Test that the size of the tuple doesn't change
  534. self.assertEqual(len(result), 10)
  535. # Make sure that assignment really fails
  536. try:
  537. result.f_bfree = 1
  538. self.fail("No exception raised")
  539. except AttributeError:
  540. pass
  541. try:
  542. result.parrot = 1
  543. self.fail("No exception raised")
  544. except AttributeError:
  545. pass
  546. # Use the constructor with a too-short tuple.
  547. try:
  548. result2 = os.statvfs_result((10,))
  549. self.fail("No exception raised")
  550. except TypeError:
  551. pass
  552. # Use the constructor with a too-long tuple.
  553. try:
  554. result2 = os.statvfs_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
  555. except TypeError:
  556. pass
  557. @unittest.skipUnless(hasattr(os, 'statvfs'),
  558. "need os.statvfs()")
  559. def test_statvfs_result_pickle(self):
  560. result = os.statvfs(self.fname)
  561. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  562. p = pickle.dumps(result, proto)
  563. self.assertIn(b'statvfs_result', p)
  564. if proto < 4:
  565. self.assertIn(b'cos\nstatvfs_result\n', p)
  566. unpickled = pickle.loads(p)
  567. self.assertEqual(result, unpickled)
  568. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  569. def test_1686475(self):
  570. # Verify that an open file can be stat'ed
  571. try:
  572. os.stat(r"c:\pagefile.sys")
  573. except FileNotFoundError:
  574. self.skipTest(r'c:\pagefile.sys does not exist')
  575. except OSError as e:
  576. self.fail("Could not stat pagefile.sys")
  577. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  578. @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
  579. def test_15261(self):
  580. # Verify that stat'ing a closed fd does not cause crash
  581. r, w = os.pipe()
  582. try:
  583. os.stat(r) # should not raise error
  584. finally:
  585. os.close(r)
  586. os.close(w)
  587. with self.assertRaises(OSError) as ctx:
  588. os.stat(r)
  589. self.assertEqual(ctx.exception.errno, errno.EBADF)
  590. def check_file_attributes(self, result):
  591. self.assertTrue(hasattr(result, 'st_file_attributes'))
  592. self.assertTrue(isinstance(result.st_file_attributes, int))
  593. self.assertTrue(0 <= result.st_file_attributes <= 0xFFFFFFFF)
  594. @unittest.skipUnless(sys.platform == "win32",
  595. "st_file_attributes is Win32 specific")
  596. def test_file_attributes(self):
  597. # test file st_file_attributes (FILE_ATTRIBUTE_DIRECTORY not set)
  598. result = os.stat(self.fname)
  599. self.check_file_attributes(result)
  600. self.assertEqual(
  601. result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY,
  602. 0)
  603. # test directory st_file_attributes (FILE_ATTRIBUTE_DIRECTORY set)
  604. dirname = os_helper.TESTFN + "dir"
  605. os.mkdir(dirname)
  606. self.addCleanup(os.rmdir, dirname)
  607. result = os.stat(dirname)
  608. self.check_file_attributes(result)
  609. self.assertEqual(
  610. result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY,
  611. stat.FILE_ATTRIBUTE_DIRECTORY)
  612. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  613. def test_access_denied(self):
  614. # Default to FindFirstFile WIN32_FIND_DATA when access is
  615. # denied. See issue 28075.
  616. # os.environ['TEMP'] should be located on a volume that
  617. # supports file ACLs.
  618. fname = os.path.join(os.environ['TEMP'], self.fname)
  619. self.addCleanup(os_helper.unlink, fname)
  620. create_file(fname, b'ABC')
  621. # Deny the right to [S]YNCHRONIZE on the file to
  622. # force CreateFile to fail with ERROR_ACCESS_DENIED.
  623. DETACHED_PROCESS = 8
  624. subprocess.check_call(
  625. # bpo-30584: Use security identifier *S-1-5-32-545 instead
  626. # of localized "Users" to not depend on the locale.
  627. ['icacls.exe', fname, '/deny', '*S-1-5-32-545:(S)'],
  628. creationflags=DETACHED_PROCESS
  629. )
  630. result = os.stat(fname)
  631. self.assertNotEqual(result.st_size, 0)
  632. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  633. def test_stat_block_device(self):
  634. # bpo-38030: os.stat fails for block devices
  635. # Test a filename like "//./C:"
  636. fname = "//./" + os.path.splitdrive(os.getcwd())[0]
  637. result = os.stat(fname)
  638. self.assertEqual(result.st_mode, stat.S_IFBLK)
  639. class UtimeTests(unittest.TestCase):
  640. def setUp(self):
  641. self.dirname = os_helper.TESTFN
  642. self.fname = os.path.join(self.dirname, "f1")
  643. self.addCleanup(os_helper.rmtree, self.dirname)
  644. os.mkdir(self.dirname)
  645. create_file(self.fname)
  646. def support_subsecond(self, filename):
  647. # Heuristic to check if the filesystem supports timestamp with
  648. # subsecond resolution: check if float and int timestamps are different
  649. st = os.stat(filename)
  650. return ((st.st_atime != st[7])
  651. or (st.st_mtime != st[8])
  652. or (st.st_ctime != st[9]))
  653. def _test_utime(self, set_time, filename=None):
  654. if not filename:
  655. filename = self.fname
  656. support_subsecond = self.support_subsecond(filename)
  657. if support_subsecond:
  658. # Timestamp with a resolution of 1 microsecond (10^-6).
  659. #
  660. # The resolution of the C internal function used by os.utime()
  661. # depends on the platform: 1 sec, 1 us, 1 ns. Writing a portable
  662. # test with a resolution of 1 ns requires more work:
  663. # see the issue #15745.
  664. atime_ns = 1002003000 # 1.002003 seconds
  665. mtime_ns = 4005006000 # 4.005006 seconds
  666. else:
  667. # use a resolution of 1 second
  668. atime_ns = 5 * 10**9
  669. mtime_ns = 8 * 10**9
  670. set_time(filename, (atime_ns, mtime_ns))
  671. st = os.stat(filename)
  672. if support_subsecond:
  673. self.assertAlmostEqual(st.st_atime, atime_ns * 1e-9, delta=1e-6)
  674. self.assertAlmostEqual(st.st_mtime, mtime_ns * 1e-9, delta=1e-6)
  675. else:
  676. self.assertEqual(st.st_atime, atime_ns * 1e-9)
  677. self.assertEqual(st.st_mtime, mtime_ns * 1e-9)
  678. self.assertEqual(st.st_atime_ns, atime_ns)
  679. self.assertEqual(st.st_mtime_ns, mtime_ns)
  680. def test_utime(self):
  681. def set_time(filename, ns):
  682. # test the ns keyword parameter
  683. os.utime(filename, ns=ns)
  684. self._test_utime(set_time)
  685. @staticmethod
  686. def ns_to_sec(ns):
  687. # Convert a number of nanosecond (int) to a number of seconds (float).
  688. # Round towards infinity by adding 0.5 nanosecond to avoid rounding
  689. # issue, os.utime() rounds towards minus infinity.
  690. return (ns * 1e-9) + 0.5e-9
  691. def test_utime_by_indexed(self):
  692. # pass times as floating point seconds as the second indexed parameter
  693. def set_time(filename, ns):
  694. atime_ns, mtime_ns = ns
  695. atime = self.ns_to_sec(atime_ns)
  696. mtime = self.ns_to_sec(mtime_ns)
  697. # test utimensat(timespec), utimes(timeval), utime(utimbuf)
  698. # or utime(time_t)
  699. os.utime(filename, (atime, mtime))
  700. self._test_utime(set_time)
  701. def test_utime_by_times(self):
  702. def set_time(filename, ns):
  703. atime_ns, mtime_ns = ns
  704. atime = self.ns_to_sec(atime_ns)
  705. mtime = self.ns_to_sec(mtime_ns)
  706. # test the times keyword parameter
  707. os.utime(filename, times=(atime, mtime))
  708. self._test_utime(set_time)
  709. @unittest.skipUnless(os.utime in os.supports_follow_symlinks,
  710. "follow_symlinks support for utime required "
  711. "for this test.")
  712. def test_utime_nofollow_symlinks(self):
  713. def set_time(filename, ns):
  714. # use follow_symlinks=False to test utimensat(timespec)
  715. # or lutimes(timeval)
  716. os.utime(filename, ns=ns, follow_symlinks=False)
  717. self._test_utime(set_time)
  718. @unittest.skipUnless(os.utime in os.supports_fd,
  719. "fd support for utime required for this test.")
  720. def test_utime_fd(self):
  721. def set_time(filename, ns):
  722. with open(filename, 'wb', 0) as fp:
  723. # use a file descriptor to test futimens(timespec)
  724. # or futimes(timeval)
  725. os.utime(fp.fileno(), ns=ns)
  726. self._test_utime(set_time)
  727. @unittest.skipUnless(os.utime in os.supports_dir_fd,
  728. "dir_fd support for utime required for this test.")
  729. def test_utime_dir_fd(self):
  730. def set_time(filename, ns):
  731. dirname, name = os.path.split(filename)
  732. with os_helper.open_dir_fd(dirname) as dirfd:
  733. # pass dir_fd to test utimensat(timespec) or futimesat(timeval)
  734. os.utime(name, dir_fd=dirfd, ns=ns)
  735. self._test_utime(set_time)
  736. def test_utime_directory(self):
  737. def set_time(filename, ns):
  738. # test calling os.utime() on a directory
  739. os.utime(filename, ns=ns)
  740. self._test_utime(set_time, filename=self.dirname)
  741. def _test_utime_current(self, set_time):
  742. # Get the system clock
  743. current = time.time()
  744. # Call os.utime() to set the timestamp to the current system clock
  745. set_time(self.fname)
  746. if not self.support_subsecond(self.fname):
  747. delta = 1.0
  748. else:
  749. # On Windows, the usual resolution of time.time() is 15.6 ms.
  750. # bpo-30649: Tolerate 50 ms for slow Windows buildbots.
  751. #
  752. # x86 Gentoo Refleaks 3.x once failed with dt=20.2 ms. So use
  753. # also 50 ms on other platforms.
  754. delta = 0.050
  755. st = os.stat(self.fname)
  756. msg = ("st_time=%r, current=%r, dt=%r"
  757. % (st.st_mtime, current, st.st_mtime - current))
  758. self.assertAlmostEqual(st.st_mtime, current,
  759. delta=delta, msg=msg)
  760. def test_utime_current(self):
  761. def set_time(filename):
  762. # Set to the current time in the new way
  763. os.utime(self.fname)
  764. self._test_utime_current(set_time)
  765. def test_utime_current_old(self):
  766. def set_time(filename):
  767. # Set to the current time in the old explicit way.
  768. os.utime(self.fname, None)
  769. self._test_utime_current(set_time)
  770. def get_file_system(self, path):
  771. if sys.platform == 'win32':
  772. root = os.path.splitdrive(os.path.abspath(path))[0] + '\\'
  773. import ctypes
  774. kernel32 = ctypes.windll.kernel32
  775. buf = ctypes.create_unicode_buffer("", 100)
  776. ok = kernel32.GetVolumeInformationW(root, None, 0,
  777. None, None, None,
  778. buf, len(buf))
  779. if ok:
  780. return buf.value
  781. # return None if the filesystem is unknown
  782. def test_large_time(self):
  783. # Many filesystems are limited to the year 2038. At least, the test
  784. # pass with NTFS filesystem.
  785. if self.get_file_system(self.dirname) != "NTFS":
  786. self.skipTest("requires NTFS")
  787. large = 5000000000 # some day in 2128
  788. os.utime(self.fname, (large, large))
  789. self.assertEqual(os.stat(self.fname).st_mtime, large)
  790. def test_utime_invalid_arguments(self):
  791. # seconds and nanoseconds parameters are mutually exclusive
  792. with self.assertRaises(ValueError):
  793. os.utime(self.fname, (5, 5), ns=(5, 5))
  794. with self.assertRaises(TypeError):
  795. os.utime(self.fname, [5, 5])
  796. with self.assertRaises(TypeError):
  797. os.utime(self.fname, (5,))
  798. with self.assertRaises(TypeError):
  799. os.utime(self.fname, (5, 5, 5))
  800. with self.assertRaises(TypeError):
  801. os.utime(self.fname, ns=[5, 5])
  802. with self.assertRaises(TypeError):
  803. os.utime(self.fname, ns=(5,))
  804. with self.assertRaises(TypeError):
  805. os.utime(self.fname, ns=(5, 5, 5))
  806. if os.utime not in os.supports_follow_symlinks:
  807. with self.assertRaises(NotImplementedError):
  808. os.utime(self.fname, (5, 5), follow_symlinks=False)
  809. if os.utime not in os.supports_fd:
  810. with open(self.fname, 'wb', 0) as fp:
  811. with self.assertRaises(TypeError):
  812. os.utime(fp.fileno(), (5, 5))
  813. if os.utime not in os.supports_dir_fd:
  814. with self.assertRaises(NotImplementedError):
  815. os.utime(self.fname, (5, 5), dir_fd=0)
  816. @support.cpython_only
  817. def test_issue31577(self):
  818. # The interpreter shouldn't crash in case utime() received a bad
  819. # ns argument.
  820. def get_bad_int(divmod_ret_val):
  821. class BadInt:
  822. def __divmod__(*args):
  823. return divmod_ret_val
  824. return BadInt()
  825. with self.assertRaises(TypeError):
  826. os.utime(self.fname, ns=(get_bad_int(42), 1))
  827. with self.assertRaises(TypeError):
  828. os.utime(self.fname, ns=(get_bad_int(()), 1))
  829. with self.assertRaises(TypeError):
  830. os.utime(self.fname, ns=(get_bad_int((1, 2, 3)), 1))
  831. from test import mapping_tests
  832. class EnvironTests(mapping_tests.BasicTestMappingProtocol):
  833. """check that os.environ object conform to mapping protocol"""
  834. type2test = None
  835. def setUp(self):
  836. self.__save = dict(os.environ)
  837. if os.supports_bytes_environ:
  838. self.__saveb = dict(os.environb)
  839. for key, value in self._reference().items():
  840. os.environ[key] = value
  841. def tearDown(self):
  842. os.environ.clear()
  843. os.environ.update(self.__save)
  844. if os.supports_bytes_environ:
  845. os.environb.clear()
  846. os.environb.update(self.__saveb)
  847. def _reference(self):
  848. return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"}
  849. def _empty_mapping(self):
  850. os.environ.clear()
  851. return os.environ
  852. # Bug 1110478
  853. @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
  854. 'requires a shell')
  855. @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
  856. @support.requires_subprocess()
  857. def test_update2(self):
  858. os.environ.clear()
  859. os.environ.update(HELLO="World")
  860. with os.popen("%s -c 'echo $HELLO'" % unix_shell) as popen:
  861. value = popen.read().strip()
  862. self.assertEqual(value, "World")
  863. @unittest.skipUnless(unix_shell and os.path.exists(unix_shell),
  864. 'requires a shell')
  865. @unittest.skipUnless(hasattr(os, 'popen'), "needs os.popen()")
  866. @support.requires_subprocess()
  867. def test_os_popen_iter(self):
  868. with os.popen("%s -c 'echo \"line1\nline2\nline3\"'"
  869. % unix_shell) as popen:
  870. it = iter(popen)
  871. self.assertEqual(next(it), "line1\n")
  872. self.assertEqual(next(it), "line2\n")
  873. self.assertEqual(next(it), "line3\n")
  874. self.assertRaises(StopIteration, next, it)
  875. # Verify environ keys and values from the OS are of the
  876. # correct str type.
  877. def test_keyvalue_types(self):
  878. for key, val in os.environ.items():
  879. self.assertEqual(type(key), str)
  880. self.assertEqual(type(val), str)
  881. def test_items(self):
  882. for key, value in self._reference().items():
  883. self.assertEqual(os.environ.get(key), value)
  884. # Issue 7310
  885. def test___repr__(self):
  886. """Check that the repr() of os.environ looks like environ({...})."""
  887. env = os.environ
  888. formatted_items = ", ".join(
  889. f"{key!r}: {value!r}"
  890. for key, value in env.items()
  891. )
  892. self.assertEqual(repr(env), f"environ({{{formatted_items}}})")
  893. def test_get_exec_path(self):
  894. defpath_list = os.defpath.split(os.pathsep)
  895. test_path = ['/monty', '/python', '', '/flying/circus']
  896. test_env = {'PATH': os.pathsep.join(test_path)}
  897. saved_environ = os.environ
  898. try:
  899. os.environ = dict(test_env)
  900. # Test that defaulting to os.environ works.
  901. self.assertSequenceEqual(test_path, os.get_exec_path())
  902. self.assertSequenceEqual(test_path, os.get_exec_path(env=None))
  903. finally:
  904. os.environ = saved_environ
  905. # No PATH environment variable
  906. self.assertSequenceEqual(defpath_list, os.get_exec_path({}))
  907. # Empty PATH environment variable
  908. self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''}))
  909. # Supplied PATH environment variable
  910. self.assertSequenceEqual(test_path, os.get_exec_path(test_env))
  911. if os.supports_bytes_environ:
  912. # env cannot contain 'PATH' and b'PATH' keys
  913. try:
  914. # ignore BytesWarning warning
  915. with warnings.catch_warnings(record=True):
  916. mixed_env = {'PATH': '1', b'PATH': b'2'}
  917. except BytesWarning:
  918. # mixed_env cannot be created with python -bb
  919. pass
  920. else:
  921. self.assertRaises(ValueError, os.get_exec_path, mixed_env)
  922. # bytes key and/or value
  923. self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}),
  924. ['abc'])
  925. self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}),
  926. ['abc'])
  927. self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}),
  928. ['abc'])
  929. @unittest.skipUnless(os.supports_bytes_environ,
  930. "os.environb required for this test.")
  931. def test_environb(self):
  932. # os.environ -> os.environb
  933. value = 'euro\u20ac'
  934. try:
  935. value_bytes = value.encode(sys.getfilesystemencoding(),
  936. 'surrogateescape')
  937. except UnicodeEncodeError:
  938. msg = "U+20AC character is not encodable to %s" % (
  939. sys.getfilesystemencoding(),)
  940. self.skipTest(msg)
  941. os.environ['unicode'] = value
  942. self.assertEqual(os.environ['unicode'], value)
  943. self.assertEqual(os.environb[b'unicode'], value_bytes)
  944. # os.environb -> os.environ
  945. value = b'\xff'
  946. os.environb[b'bytes'] = value
  947. self.assertEqual(os.environb[b'bytes'], value)
  948. value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
  949. self.assertEqual(os.environ['bytes'], value_str)
  950. @support.requires_subprocess()
  951. def test_putenv_unsetenv(self):
  952. name = "PYTHONTESTVAR"
  953. value = "testvalue"
  954. code = f'import os; print(repr(os.environ.get({name!r})))'
  955. with os_helper.EnvironmentVarGuard() as env:
  956. env.pop(name, None)
  957. os.putenv(name, value)
  958. proc = subprocess.run([sys.executable, '-c', code], check=True,
  959. stdout=subprocess.PIPE, text=True)
  960. self.assertEqual(proc.stdout.rstrip(), repr(value))
  961. os.unsetenv(name)
  962. proc = subprocess.run([sys.executable, '-c', code], check=True,
  963. stdout=subprocess.PIPE, text=True)
  964. self.assertEqual(proc.stdout.rstrip(), repr(None))
  965. # On OS X < 10.6, unsetenv() doesn't return a value (bpo-13415).
  966. @support.requires_mac_ver(10, 6)
  967. def test_putenv_unsetenv_error(self):
  968. # Empty variable name is invalid.
  969. # "=" and null character are not allowed in a variable name.
  970. for name in ('', '=name', 'na=me', 'name=', 'name\0', 'na\0me'):
  971. self.assertRaises((OSError, ValueError), os.putenv, name, "value")
  972. self.assertRaises((OSError, ValueError), os.unsetenv, name)
  973. if sys.platform == "win32":
  974. # On Windows, an environment variable string ("name=value" string)
  975. # is limited to 32,767 characters
  976. longstr = 'x' * 32_768
  977. self.assertRaises(ValueError, os.putenv, longstr, "1")
  978. self.assertRaises(ValueError, os.putenv, "X", longstr)
  979. self.assertRaises(ValueError, os.unsetenv, longstr)
  980. def test_key_type(self):
  981. missing = 'missingkey'
  982. self.assertNotIn(missing, os.environ)
  983. with self.assertRaises(KeyError) as cm:
  984. os.environ[missing]
  985. self.assertIs(cm.exception.args[0], missing)
  986. self.assertTrue(cm.exception.__suppress_context__)
  987. with self.assertRaises(KeyError) as cm:
  988. del os.environ[missing]
  989. self.assertIs(cm.exception.args[0], missing)
  990. self.assertTrue(cm.exception.__suppress_context__)
  991. def _test_environ_iteration(self, collection):
  992. iterator = iter(collection)
  993. new_key = "__new_key__"
  994. next(iterator) # start iteration over os.environ.items
  995. # add a new key in os.environ mapping
  996. os.environ[new_key] = "test_environ_iteration"
  997. try:
  998. next(iterator) # force iteration over modified mapping
  999. self.assertEqual(os.environ[new_key], "test_environ_iteration")
  1000. finally:
  1001. del os.environ[new_key]
  1002. def test_iter_error_when_changing_os_environ(self):
  1003. self._test_environ_iteration(os.environ)
  1004. def test_iter_error_when_changing_os_environ_items(self):
  1005. self._test_environ_iteration(os.environ.items())
  1006. def test_iter_error_when_changing_os_environ_values(self):
  1007. self._test_environ_iteration(os.environ.values())
  1008. def _test_underlying_process_env(self, var, expected):
  1009. if not (unix_shell and os.path.exists(unix_shell)):
  1010. return
  1011. elif not support.has_subprocess_support:
  1012. return
  1013. with os.popen(f"{unix_shell} -c 'echo ${var}'") as popen:
  1014. value = popen.read().strip()
  1015. self.assertEqual(expected, value)
  1016. def test_or_operator(self):
  1017. overridden_key = '_TEST_VAR_'
  1018. original_value = 'original_value'
  1019. os.environ[overridden_key] = original_value
  1020. new_vars_dict = {'_A_': '1', '_B_': '2', overridden_key: '3'}
  1021. expected = dict(os.environ)
  1022. expected.update(new_vars_dict)
  1023. actual = os.environ | new_vars_dict
  1024. self.assertDictEqual(expected, actual)
  1025. self.assertEqual('3', actual[overridden_key])
  1026. new_vars_items = new_vars_dict.items()
  1027. self.assertIs(NotImplemented, os.environ.__or__(new_vars_items))
  1028. self._test_underlying_process_env('_A_', '')
  1029. self._test_underlying_process_env(overridden_key, original_value)
  1030. def test_ior_operator(self):
  1031. overridden_key = '_TEST_VAR_'
  1032. os.environ[overridden_key] = 'original_value'
  1033. new_vars_dict = {'_A_': '1', '_B_': '2', overridden_key: '3'}
  1034. expected = dict(os.environ)
  1035. expected.update(new_vars_dict)
  1036. os.environ |= new_vars_dict
  1037. self.assertEqual(expected, os.environ)
  1038. self.assertEqual('3', os.environ[overridden_key])
  1039. self._test_underlying_process_env('_A_', '1')
  1040. self._test_underlying_process_env(overridden_key, '3')
  1041. def test_ior_operator_invalid_dicts(self):
  1042. os_environ_copy = os.environ.copy()
  1043. with self.assertRaises(TypeError):
  1044. dict_with_bad_key = {1: '_A_'}
  1045. os.environ |= dict_with_bad_key
  1046. with self.assertRaises(TypeError):
  1047. dict_with_bad_val = {'_A_': 1}
  1048. os.environ |= dict_with_bad_val
  1049. # Check nothing was added.
  1050. self.assertEqual(os_environ_copy, os.environ)
  1051. def test_ior_operator_key_value_iterable(self):
  1052. overridden_key = '_TEST_VAR_'
  1053. os.environ[overridden_key] = 'original_value'
  1054. new_vars_items = (('_A_', '1'), ('_B_', '2'), (overridden_key, '3'))
  1055. expected = dict(os.environ)
  1056. expected.update(new_vars_items)
  1057. os.environ |= new_vars_items
  1058. self.assertEqual(expected, os.environ)
  1059. self.assertEqual('3', os.environ[overridden_key])
  1060. self._test_underlying_process_env('_A_', '1')
  1061. self._test_underlying_process_env(overridden_key, '3')
  1062. def test_ror_operator(self):
  1063. overridden_key = '_TEST_VAR_'
  1064. original_value = 'original_value'
  1065. os.environ[overridden_key] = original_value
  1066. new_vars_dict = {'_A_': '1', '_B_': '2', overridden_key: '3'}
  1067. expected = dict(new_vars_dict)
  1068. expected.update(os.environ)
  1069. actual = new_vars_dict | os.environ
  1070. self.assertDictEqual(expected, actual)
  1071. self.assertEqual(original_value, actual[overridden_key])
  1072. new_vars_items = new_vars_dict.items()
  1073. self.assertIs(NotImplemented, os.environ.__ror__(new_vars_items))
  1074. self._test_underlying_process_env('_A_', '')
  1075. self._test_underlying_process_env(overridden_key, original_value)
  1076. class WalkTests(unittest.TestCase):
  1077. """Tests for os.walk()."""
  1078. # Wrapper to hide minor differences between os.walk and os.fwalk
  1079. # to tests both functions with the same code base
  1080. def walk(self, top, **kwargs):
  1081. if 'follow_symlinks' in kwargs:
  1082. kwargs['followlinks'] = kwargs.pop('follow_symlinks')
  1083. return os.walk(top, **kwargs)
  1084. def setUp(self):
  1085. join = os.path.join
  1086. self.addCleanup(os_helper.rmtree, os_helper.TESTFN)
  1087. # Build:
  1088. # TESTFN/
  1089. # TEST1/ a file kid and two directory kids
  1090. # tmp1
  1091. # SUB1/ a file kid and a directory kid
  1092. # tmp2
  1093. # SUB11/ no kids
  1094. # SUB2/ a file kid and a dirsymlink kid
  1095. # tmp3
  1096. # SUB21/ not readable
  1097. # tmp5
  1098. # link/ a symlink to TESTFN.2
  1099. # broken_link
  1100. # broken_link2
  1101. # broken_link3
  1102. # TEST2/
  1103. # tmp4 a lone file
  1104. self.walk_path = join(os_helper.TESTFN, "TEST1")
  1105. self.sub1_path = join(self.walk_path, "SUB1")
  1106. self.sub11_path = join(self.sub1_path, "SUB11")
  1107. sub2_path = join(self.walk_path, "SUB2")
  1108. sub21_path = join(sub2_path, "SUB21")
  1109. tmp1_path = join(self.walk_path, "tmp1")
  1110. tmp2_path = join(self.sub1_path, "tmp2")
  1111. tmp3_path = join(sub2_path, "tmp3")
  1112. tmp5_path = join(sub21_path, "tmp3")
  1113. self.link_path = join(sub2_path, "link")
  1114. t2_path = join(os_helper.TESTFN, "TEST2")
  1115. tmp4_path = join(os_helper.TESTFN, "TEST2", "tmp4")
  1116. broken_link_path = join(sub2_path, "broken_link")
  1117. broken_link2_path = join(sub2_path, "broken_link2")
  1118. broken_link3_path = join(sub2_path, "broken_link3")
  1119. # Create stuff.
  1120. os.makedirs(self.sub11_path)
  1121. os.makedirs(sub2_path)
  1122. os.makedirs(sub21_path)
  1123. os.makedirs(t2_path)
  1124. for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path, tmp5_path:
  1125. with open(path, "x", encoding='utf-8') as f:
  1126. f.write("I'm " + path + " and proud of it. Blame test_os.\n")
  1127. if os_helper.can_symlink():
  1128. os.symlink(os.path.abspath(t2_path), self.link_path)
  1129. os.symlink('broken', broken_link_path, True)
  1130. os.symlink(join('tmp3', 'broken'), broken_link2_path, True)
  1131. os.symlink(join('SUB21', 'tmp5'), broken_link3_path, True)
  1132. self.sub2_tree = (sub2_path, ["SUB21", "link"],
  1133. ["broken_link", "broken_link2", "broken_link3",
  1134. "tmp3"])
  1135. else:
  1136. self.sub2_tree = (sub2_path, ["SUB21"], ["tmp3"])
  1137. if not support.is_emscripten:
  1138. # Emscripten fails with inaccessible directory
  1139. os.chmod(sub21_path, 0)
  1140. try:
  1141. os.listdir(sub21_path)
  1142. except PermissionError:
  1143. self.addCleanup(os.chmod, sub21_path, stat.S_IRWXU)
  1144. else:
  1145. os.chmod(sub21_path, stat.S_IRWXU)
  1146. os.unlink(tmp5_path)
  1147. os.rmdir(sub21_path)
  1148. del self.sub2_tree[1][:1]
  1149. def test_walk_topdown(self):
  1150. # Walk top-down.
  1151. all = list(self.walk(self.walk_path))
  1152. self.assertEqual(len(all), 4)
  1153. # We can't know which order SUB1 and SUB2 will appear in.
  1154. # Not flipped: TESTFN, SUB1, SUB11, SUB2
  1155. # flipped: TESTFN, SUB2, SUB1, SUB11
  1156. flipped = all[0][1][0] != "SUB1"
  1157. all[0][1].sort()
  1158. all[3 - 2 * flipped][-1].sort()
  1159. all[3 - 2 * flipped][1].sort()
  1160. self.assertEqual(all[0], (self.walk_path, ["SUB1", "SUB2"], ["tmp1"]))
  1161. self.assertEqual(all[1 + flipped], (self.sub1_path, ["SUB11"], ["tmp2"]))
  1162. self.assertEqual(all[2 + flipped], (self.sub11_path, [], []))
  1163. self.assertEqual(all[3 - 2 * flipped], self.sub2_tree)
  1164. def test_walk_prune(self, walk_path=None):
  1165. if walk_path is None:
  1166. walk_path = self.walk_path
  1167. # Prune the search.
  1168. all = []
  1169. for root, dirs, files in self.walk(walk_path):
  1170. all.append((root, dirs, files))
  1171. # Don't descend into SUB1.
  1172. if 'SUB1' in dirs:
  1173. # Note that this also mutates the dirs we appended to all!
  1174. dirs.remove('SUB1')
  1175. self.assertEqual(len(all), 2)
  1176. self.assertEqual(all[0], (self.walk_path, ["SUB2"], ["tmp1"]))
  1177. all[1][-1].sort()
  1178. all[1][1].sort()
  1179. self.assertEqual(all[1], self.sub2_tree)
  1180. def test_file_like_path(self):
  1181. self.test_walk_prune(FakePath(self.walk_path))
  1182. def test_walk_bottom_up(self):
  1183. # Walk bottom-up.
  1184. all = list(self.walk(self.walk_path, topdown=False))
  1185. self.assertEqual(len(all), 4, all)
  1186. # We can't know which order SUB1 and SUB2 will appear in.
  1187. # Not flipped: SUB11, SUB1, SUB2, TESTFN
  1188. # flipped: SUB2, SUB11, SUB1, TESTFN
  1189. flipped = all[3][1][0] != "SUB1"
  1190. all[3][1].sort()
  1191. all[2 - 2 * flipped][-1].sort()
  1192. all[2 - 2 * flipped][1].sort()
  1193. self.assertEqual(all[3],
  1194. (self.walk_path, ["SUB1", "SUB2"], ["tmp1"]))
  1195. self.assertEqual(all[flipped],
  1196. (self.sub11_path, [], []))
  1197. self.assertEqual(all[flipped + 1],
  1198. (self.sub1_path, ["SUB11"], ["tmp2"]))
  1199. self.assertEqual(all[2 - 2 * flipped],
  1200. self.sub2_tree)
  1201. def test_walk_symlink(self):
  1202. if not os_helper.can_symlink():
  1203. self.skipTest("need symlink support")
  1204. # Walk, following symlinks.
  1205. walk_it = self.walk(self.walk_path, follow_symlinks=True)
  1206. for root, dirs, files in walk_it:
  1207. if root == self.link_path:
  1208. self.assertEqual(dirs, [])
  1209. self.assertEqual(files, ["tmp4"])
  1210. break
  1211. else:
  1212. self.fail("Didn't follow symlink with followlinks=True")
  1213. def test_walk_bad_dir(self):
  1214. # Walk top-down.
  1215. errors = []
  1216. walk_it = self.walk(self.walk_path, onerror=errors.append)
  1217. root, dirs, files = next(walk_it)
  1218. self.assertEqual(errors, [])
  1219. dir1 = 'SUB1'
  1220. path1 = os.path.join(root, dir1)
  1221. path1new = os.path.join(root, dir1 + '.new')
  1222. os.rename(path1, path1new)
  1223. try:
  1224. roots = [r for r, d, f in walk_it]
  1225. self.assertTrue(errors)
  1226. self.assertNotIn(path1, roots)
  1227. self.assertNotIn(path1new, roots)
  1228. for dir2 in dirs:
  1229. if dir2 != dir1:
  1230. self.assertIn(os.path.join(root, dir2), roots)
  1231. finally:
  1232. os.rename(path1new, path1)
  1233. def test_walk_many_open_files(self):
  1234. depth = 30
  1235. base = os.path.join(os_helper.TESTFN, 'deep')
  1236. p = os.path.join(base, *(['d']*depth))
  1237. os.makedirs(p)
  1238. iters = [self.walk(base, topdown=False) for j in range(100)]
  1239. for i in range(depth + 1):
  1240. expected = (p, ['d'] if i else [], [])
  1241. for it in iters:
  1242. self.assertEqual(next(it), expected)
  1243. p = os.path.dirname(p)
  1244. iters = [self.walk(base, topdown=True) for j in range(100)]
  1245. p = base
  1246. for i in range(depth + 1):
  1247. expected = (p, ['d'] if i < depth else [], [])
  1248. for it in iters:
  1249. self.assertEqual(next(it), expected)
  1250. p = os.path.join(p, 'd')
  1251. @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
  1252. class FwalkTests(WalkTests):
  1253. """Tests for os.fwalk()."""
  1254. def walk(self, top, **kwargs):
  1255. for root, dirs, files, root_fd in self.fwalk(top, **kwargs):
  1256. yield (root, dirs, files)
  1257. def fwalk(self, *args, **kwargs):
  1258. return os.fwalk(*args, **kwargs)
  1259. def _compare_to_walk(self, walk_kwargs, fwalk_kwargs):
  1260. """
  1261. compare with walk() results.
  1262. """
  1263. walk_kwargs = walk_kwargs.copy()
  1264. fwalk_kwargs = fwalk_kwargs.copy()
  1265. for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
  1266. walk_kwargs.update(topdown=topdown, followlinks=follow_symlinks)
  1267. fwalk_kwargs.update(topdown=topdown, follow_symlinks=follow_symlinks)
  1268. expected = {}
  1269. for root, dirs, files in os.walk(**walk_kwargs):
  1270. expected[root] = (set(dirs), set(files))
  1271. for root, dirs, files, rootfd in self.fwalk(**fwalk_kwargs):
  1272. self.assertIn(root, expected)
  1273. self.assertEqual(expected[root], (set(dirs), set(files)))
  1274. def test_compare_to_walk(self):
  1275. kwargs = {'top': os_helper.TESTFN}
  1276. self._compare_to_walk(kwargs, kwargs)
  1277. def test_dir_fd(self):
  1278. try:
  1279. fd = os.open(".", os.O_RDONLY)
  1280. walk_kwargs = {'top': os_helper.TESTFN}
  1281. fwalk_kwargs = walk_kwargs.copy()
  1282. fwalk_kwargs['dir_fd'] = fd
  1283. self._compare_to_walk(walk_kwargs, fwalk_kwargs)
  1284. finally:
  1285. os.close(fd)
  1286. def test_yields_correct_dir_fd(self):
  1287. # check returned file descriptors
  1288. for topdown, follow_symlinks in itertools.product((True, False), repeat=2):
  1289. args = os_helper.TESTFN, topdown, None
  1290. for root, dirs, files, rootfd in self.fwalk(*args, follow_symlinks=follow_symlinks):
  1291. # check that the FD is valid
  1292. os.fstat(rootfd)
  1293. # redundant check
  1294. os.stat(rootfd)
  1295. # check that listdir() returns consistent information
  1296. self.assertEqual(set(os.listdir(rootfd)), set(dirs) | set(files))
  1297. @unittest.skipIf(
  1298. support.is_emscripten, "Cannot dup stdout on Emscripten"
  1299. )
  1300. def test_fd_leak(self):
  1301. # Since we're opening a lot of FDs, we must be careful to avoid leaks:
  1302. # we both check that calling fwalk() a large number of times doesn't
  1303. # yield EMFILE, and that the minimum allocated FD hasn't changed.
  1304. minfd = os.dup(1)
  1305. os.close(minfd)
  1306. for i in range(256):
  1307. for x in self.fwalk(os_helper.TESTFN):
  1308. pass
  1309. newfd = os.dup(1)
  1310. self.addCleanup(os.close, newfd)
  1311. self.assertEqual(newfd, minfd)
  1312. # fwalk() keeps file descriptors open
  1313. test_walk_many_open_files = None
  1314. class BytesWalkTests(WalkTests):
  1315. """Tests for os.walk() with bytes."""
  1316. def walk(self, top, **kwargs):
  1317. if 'follow_symlinks' in kwargs:
  1318. kwargs['followlinks'] = kwargs.pop('follow_symlinks')
  1319. for broot, bdirs, bfiles in os.walk(os.fsencode(top), **kwargs):
  1320. root = os.fsdecode(broot)
  1321. dirs = list(map(os.fsdecode, bdirs))
  1322. files = list(map(os.fsdecode, bfiles))
  1323. yield (root, dirs, files)
  1324. bdirs[:] = list(map(os.fsencode, dirs))
  1325. bfiles[:] = list(map(os.fsencode, files))
  1326. @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
  1327. class BytesFwalkTests(FwalkTests):
  1328. """Tests for os.walk() with bytes."""
  1329. def fwalk(self, top='.', *args, **kwargs):
  1330. for broot, bdirs, bfiles, topfd in os.fwalk(os.fsencode(top), *args, **kwargs):
  1331. root = os.fsdecode(broot)
  1332. dirs = list(map(os.fsdecode, bdirs))
  1333. files = list(map(os.fsdecode, bfiles))
  1334. yield (root, dirs, files, topfd)
  1335. bdirs[:] = list(map(os.fsencode, dirs))
  1336. bfiles[:] = list(map(os.fsencode, files))
  1337. class MakedirTests(unittest.TestCase):
  1338. def setUp(self):
  1339. os.mkdir(os_helper.TESTFN)
  1340. def test_makedir(self):
  1341. base = os_helper.TESTFN
  1342. path = os.path.join(base, 'dir1', 'dir2', 'dir3')
  1343. os.makedirs(path) # Should work
  1344. path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4')
  1345. os.makedirs(path)
  1346. # Try paths with a '.' in them
  1347. self.assertRaises(OSError, os.makedirs, os.curdir)
  1348. path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
  1349. os.makedirs(path)
  1350. path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
  1351. 'dir5', 'dir6')
  1352. os.makedirs(path)
  1353. @unittest.skipIf(
  1354. support.is_emscripten or support.is_wasi,
  1355. "Emscripten's/WASI's umask is a stub."
  1356. )
  1357. def test_mode(self):
  1358. with os_helper.temp_umask(0o002):
  1359. base = os_helper.TESTFN
  1360. parent = os.path.join(base, 'dir1')
  1361. path = os.path.join(parent, 'dir2')
  1362. os.makedirs(path, 0o555)
  1363. self.assertTrue(os.path.exists(path))
  1364. self.assertTrue(os.path.isdir(path))
  1365. if os.name != 'nt':
  1366. self.assertEqual(os.stat(path).st_mode & 0o777, 0o555)
  1367. self.assertEqual(os.stat(parent).st_mode & 0o777, 0o775)
  1368. @unittest.skipIf(
  1369. support.is_emscripten or support.is_wasi,
  1370. "Emscripten's/WASI's umask is a stub."
  1371. )
  1372. def test_exist_ok_existing_directory(self):
  1373. path = os.path.join(os_helper.TESTFN, 'dir1')
  1374. mode = 0o777
  1375. old_mask = os.umask(0o022)
  1376. os.makedirs(path, mode)
  1377. self.assertRaises(OSError, os.makedirs, path, mode)
  1378. self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
  1379. os.makedirs(path, 0o776, exist_ok=True)
  1380. os.makedirs(path, mode=mode, exist_ok=True)
  1381. os.umask(old_mask)
  1382. # Issue #25583: A drive root could raise PermissionError on Windows
  1383. os.makedirs(os.path.abspath('/'), exist_ok=True)
  1384. @unittest.skipIf(
  1385. support.is_emscripten or support.is_wasi,
  1386. "Emscripten's/WASI's umask is a stub."
  1387. )
  1388. def test_exist_ok_s_isgid_directory(self):
  1389. path = os.path.join(os_helper.TESTFN, 'dir1')
  1390. S_ISGID = stat.S_ISGID
  1391. mode = 0o777
  1392. old_mask = os.umask(0o022)
  1393. try:
  1394. existing_testfn_mode = stat.S_IMODE(
  1395. os.lstat(os_helper.TESTFN).st_mode)
  1396. try:
  1397. os.chmod(os_helper.TESTFN, existing_testfn_mode | S_ISGID)
  1398. except PermissionError:
  1399. raise unittest.SkipTest('Cannot set S_ISGID for dir.')
  1400. if (os.lstat(os_helper.TESTFN).st_mode & S_ISGID != S_ISGID):
  1401. raise unittest.SkipTest('No support for S_ISGID dir mode.')
  1402. # The os should apply S_ISGID from the parent dir for us, but
  1403. # this test need not depend on that behavior. Be explicit.
  1404. os.makedirs(path, mode | S_ISGID)
  1405. # http://bugs.python.org/issue14992
  1406. # Should not fail when the bit is already set.
  1407. os.makedirs(path, mode, exist_ok=True)
  1408. # remove the bit.
  1409. os.chmod(path, stat.S_IMODE(os.lstat(path).st_mode) & ~S_ISGID)
  1410. # May work even when the bit is not already set when demanded.
  1411. os.makedirs(path, mode | S_ISGID, exist_ok=True)
  1412. finally:
  1413. os.umask(old_mask)
  1414. def test_exist_ok_existing_regular_file(self):
  1415. base = os_helper.TESTFN
  1416. path = os.path.join(os_helper.TESTFN, 'dir1')
  1417. with open(path, 'w', encoding='utf-8') as f:
  1418. f.write('abc')
  1419. self.assertRaises(OSError, os.makedirs, path)
  1420. self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
  1421. self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
  1422. os.remove(path)
  1423. def tearDown(self):
  1424. path = os.path.join(os_helper.TESTFN, 'dir1', 'dir2', 'dir3',
  1425. 'dir4', 'dir5', 'dir6')
  1426. # If the tests failed, the bottom-most directory ('../dir6')
  1427. # may not have been created, so we look for the outermost directory
  1428. # that exists.
  1429. while not os.path.exists(path) and path != os_helper.TESTFN:
  1430. path = os.path.dirname(path)
  1431. os.removedirs(path)
  1432. @os_helper.skip_unless_working_chmod
  1433. class ChownFileTests(unittest.TestCase):
  1434. @classmethod
  1435. def setUpClass(cls):
  1436. os.mkdir(os_helper.TESTFN)
  1437. def test_chown_uid_gid_arguments_must_be_index(self):
  1438. stat = os.stat(os_helper.TESTFN)
  1439. uid = stat.st_uid
  1440. gid = stat.st_gid
  1441. for value in (-1.0, -1j, decimal.Decimal(-1), fractions.Fraction(-2, 2)):
  1442. self.assertRaises(TypeError, os.chown, os_helper.TESTFN, value, gid)
  1443. self.assertRaises(TypeError, os.chown, os_helper.TESTFN, uid, value)
  1444. self.assertIsNone(os.chown(os_helper.TESTFN, uid, gid))
  1445. self.assertIsNone(os.chown(os_helper.TESTFN, -1, -1))
  1446. @unittest.skipUnless(hasattr(os, 'getgroups'), 'need os.getgroups')
  1447. def test_chown_gid(self):
  1448. groups = os.getgroups()
  1449. if len(groups) < 2:
  1450. self.skipTest("test needs at least 2 groups")
  1451. gid_1, gid_2 = groups[:2]
  1452. uid = os.stat(os_helper.TESTFN).st_uid
  1453. os.chown(os_helper.TESTFN, uid, gid_1)
  1454. gid = os.stat(os_helper.TESTFN).st_gid
  1455. self.assertEqual(gid, gid_1)
  1456. os.chown(os_helper.TESTFN, uid, gid_2)
  1457. gid = os.stat(os_helper.TESTFN).st_gid
  1458. self.assertEqual(gid, gid_2)
  1459. @unittest.skipUnless(root_in_posix and len(all_users) > 1,
  1460. "test needs root privilege and more than one user")
  1461. def test_chown_with_root(self):
  1462. uid_1, uid_2 = all_users[:2]
  1463. gid = os.stat(os_helper.TESTFN).st_gid
  1464. os.chown(os_helper.TESTFN, uid_1, gid)
  1465. uid = os.stat(os_helper.TESTFN).st_uid
  1466. self.assertEqual(uid, uid_1)
  1467. os.chown(os_helper.TESTFN, uid_2, gid)
  1468. uid = os.stat(os_helper.TESTFN).st_uid
  1469. self.assertEqual(uid, uid_2)
  1470. @unittest.skipUnless(not root_in_posix and len(all_users) > 1,
  1471. "test needs non-root account and more than one user")
  1472. def test_chown_without_permission(self):
  1473. uid_1, uid_2 = all_users[:2]
  1474. gid = os.stat(os_helper.TESTFN).st_gid
  1475. with self.assertRaises(PermissionError):
  1476. os.chown(os_helper.TESTFN, uid_1, gid)
  1477. os.chown(os_helper.TESTFN, uid_2, gid)
  1478. @classmethod
  1479. def tearDownClass(cls):
  1480. os.rmdir(os_helper.TESTFN)
  1481. class RemoveDirsTests(unittest.TestCase):
  1482. def setUp(self):
  1483. os.makedirs(os_helper.TESTFN)
  1484. def tearDown(self):
  1485. os_helper.rmtree(os_helper.TESTFN)
  1486. def test_remove_all(self):
  1487. dira = os.path.join(os_helper.TESTFN, 'dira')
  1488. os.mkdir(dira)
  1489. dirb = os.path.join(dira, 'dirb')
  1490. os.mkdir(dirb)
  1491. os.removedirs(dirb)
  1492. self.assertFalse(os.path.exists(dirb))
  1493. self.assertFalse(os.path.exists(dira))
  1494. self.assertFalse(os.path.exists(os_helper.TESTFN))
  1495. def test_remove_partial(self):
  1496. dira = os.path.join(os_helper.TESTFN, 'dira')
  1497. os.mkdir(dira)
  1498. dirb = os.path.join(dira, 'dirb')
  1499. os.mkdir(dirb)
  1500. create_file(os.path.join(dira, 'file.txt'))
  1501. os.removedirs(dirb)
  1502. self.assertFalse(os.path.exists(dirb))
  1503. self.assertTrue(os.path.exists(dira))
  1504. self.assertTrue(os.path.exists(os_helper.TESTFN))
  1505. def test_remove_nothing(self):
  1506. dira = os.path.join(os_helper.TESTFN, 'dira')
  1507. os.mkdir(dira)
  1508. dirb = os.path.join(dira, 'dirb')
  1509. os.mkdir(dirb)
  1510. create_file(os.path.join(dirb, 'file.txt'))
  1511. with self.assertRaises(OSError):
  1512. os.removedirs(dirb)
  1513. self.assertTrue(os.path.exists(dirb))
  1514. self.assertTrue(os.path.exists(dira))
  1515. self.assertTrue(os.path.exists(os_helper.TESTFN))
  1516. @unittest.skipIf(support.is_wasi, "WASI has no /dev/null")
  1517. class DevNullTests(unittest.TestCase):
  1518. def test_devnull(self):
  1519. with open(os.devnull, 'wb', 0) as f:
  1520. f.write(b'hello')
  1521. f.close()
  1522. with open(os.devnull, 'rb') as f:
  1523. self.assertEqual(f.read(), b'')
  1524. class URandomTests(unittest.TestCase):
  1525. def test_urandom_length(self):
  1526. self.assertEqual(len(os.urandom(0)), 0)
  1527. self.assertEqual(len(os.urandom(1)), 1)
  1528. self.assertEqual(len(os.urandom(10)), 10)
  1529. self.assertEqual(len(os.urandom(100)), 100)
  1530. self.assertEqual(len(os.urandom(1000)), 1000)
  1531. def test_urandom_value(self):
  1532. data1 = os.urandom(16)
  1533. self.assertIsInstance(data1, bytes)
  1534. data2 = os.urandom(16)
  1535. self.assertNotEqual(data1, data2)
  1536. def get_urandom_subprocess(self, count):
  1537. code = '\n'.join((
  1538. 'import os, sys',
  1539. 'data = os.urandom(%s)' % count,
  1540. 'sys.stdout.buffer.write(data)',
  1541. 'sys.stdout.buffer.flush()'))
  1542. out = assert_python_ok('-c', code)
  1543. stdout = out[1]
  1544. self.assertEqual(len(stdout), count)
  1545. return stdout
  1546. def test_urandom_subprocess(self):
  1547. data1 = self.get_urandom_subprocess(16)
  1548. data2 = self.get_urandom_subprocess(16)
  1549. self.assertNotEqual(data1, data2)
  1550. @unittest.skipUnless(hasattr(os, 'getrandom'), 'need os.getrandom()')
  1551. class GetRandomTests(unittest.TestCase):
  1552. @classmethod
  1553. def setUpClass(cls):
  1554. try:
  1555. os.getrandom(1)
  1556. except OSError as exc:
  1557. if exc.errno == errno.ENOSYS:
  1558. # Python compiled on a more recent Linux version
  1559. # than the current Linux kernel
  1560. raise unittest.SkipTest("getrandom() syscall fails with ENOSYS")
  1561. else:
  1562. raise
  1563. def test_getrandom_type(self):
  1564. data = os.getrandom(16)
  1565. self.assertIsInstance(data, bytes)
  1566. self.assertEqual(len(data), 16)
  1567. def test_getrandom0(self):
  1568. empty = os.getrandom(0)
  1569. self.assertEqual(empty, b'')
  1570. def test_getrandom_random(self):
  1571. self.assertTrue(hasattr(os, 'GRND_RANDOM'))
  1572. # Don't test os.getrandom(1, os.GRND_RANDOM) to not consume the rare
  1573. # resource /dev/random
  1574. def test_getrandom_nonblock(self):
  1575. # The call must not fail. Check also that the flag exists
  1576. try:
  1577. os.getrandom(1, os.GRND_NONBLOCK)
  1578. except BlockingIOError:
  1579. # System urandom is not initialized yet
  1580. pass
  1581. def test_getrandom_value(self):
  1582. data1 = os.getrandom(16)
  1583. data2 = os.getrandom(16)
  1584. self.assertNotEqual(data1, data2)
  1585. # os.urandom() doesn't use a file descriptor when it is implemented with the
  1586. # getentropy() function, the getrandom() function or the getrandom() syscall
  1587. OS_URANDOM_DONT_USE_FD = (
  1588. sysconfig.get_config_var('HAVE_GETENTROPY') == 1
  1589. or sysconfig.get_config_var('HAVE_GETRANDOM') == 1
  1590. or sysconfig.get_config_var('HAVE_GETRANDOM_SYSCALL') == 1)
  1591. @unittest.skipIf(OS_URANDOM_DONT_USE_FD ,
  1592. "os.random() does not use a file descriptor")
  1593. @unittest.skipIf(sys.platform == "vxworks",
  1594. "VxWorks can't set RLIMIT_NOFILE to 1")
  1595. class URandomFDTests(unittest.TestCase):
  1596. @unittest.skipUnless(resource, "test requires the resource module")
  1597. def test_urandom_failure(self):
  1598. # Check urandom() failing when it is not able to open /dev/random.
  1599. # We spawn a new process to make the test more robust (if getrlimit()
  1600. # failed to restore the file descriptor limit after this, the whole
  1601. # test suite would crash; this actually happened on the OS X Tiger
  1602. # buildbot).
  1603. code = """if 1:
  1604. import errno
  1605. import os
  1606. import resource
  1607. soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
  1608. resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
  1609. try:
  1610. os.urandom(16)
  1611. except OSError as e:
  1612. assert e.errno == errno.EMFILE, e.errno
  1613. else:
  1614. raise AssertionError("OSError not raised")
  1615. """
  1616. assert_python_ok('-c', code)
  1617. def test_urandom_fd_closed(self):
  1618. # Issue #21207: urandom() should reopen its fd to /dev/urandom if
  1619. # closed.
  1620. code = """if 1:
  1621. import os
  1622. import sys
  1623. import test.support
  1624. os.urandom(4)
  1625. with test.support.SuppressCrashReport():
  1626. os.closerange(3, 256)
  1627. sys.stdout.buffer.write(os.urandom(4))
  1628. """
  1629. rc, out, err = assert_python_ok('-Sc', code)
  1630. def test_urandom_fd_reopened(self):
  1631. # Issue #21207: urandom() should detect its fd to /dev/urandom
  1632. # changed to something else, and reopen it.
  1633. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  1634. create_file(os_helper.TESTFN, b"x" * 256)
  1635. code = """if 1:
  1636. import os
  1637. import sys
  1638. import test.support
  1639. os.urandom(4)
  1640. with test.support.SuppressCrashReport():
  1641. for fd in range(3, 256):
  1642. try:
  1643. os.close(fd)
  1644. except OSError:
  1645. pass
  1646. else:
  1647. # Found the urandom fd (XXX hopefully)
  1648. break
  1649. os.closerange(3, 256)
  1650. with open({TESTFN!r}, 'rb') as f:
  1651. new_fd = f.fileno()
  1652. # Issue #26935: posix allows new_fd and fd to be equal but
  1653. # some libc implementations have dup2 return an error in this
  1654. # case.
  1655. if new_fd != fd:
  1656. os.dup2(new_fd, fd)
  1657. sys.stdout.buffer.write(os.urandom(4))
  1658. sys.stdout.buffer.write(os.urandom(4))
  1659. """.format(TESTFN=os_helper.TESTFN)
  1660. rc, out, err = assert_python_ok('-Sc', code)
  1661. self.assertEqual(len(out), 8)
  1662. self.assertNotEqual(out[0:4], out[4:8])
  1663. rc, out2, err2 = assert_python_ok('-Sc', code)
  1664. self.assertEqual(len(out2), 8)
  1665. self.assertNotEqual(out2, out)
  1666. @contextlib.contextmanager
  1667. def _execvpe_mockup(defpath=None):
  1668. """
  1669. Stubs out execv and execve functions when used as context manager.
  1670. Records exec calls. The mock execv and execve functions always raise an
  1671. exception as they would normally never return.
  1672. """
  1673. # A list of tuples containing (function name, first arg, args)
  1674. # of calls to execv or execve that have been made.
  1675. calls = []
  1676. def mock_execv(name, *args):
  1677. calls.append(('execv', name, args))
  1678. raise RuntimeError("execv called")
  1679. def mock_execve(name, *args):
  1680. calls.append(('execve', name, args))
  1681. raise OSError(errno.ENOTDIR, "execve called")
  1682. try:
  1683. orig_execv = os.execv
  1684. orig_execve = os.execve
  1685. orig_defpath = os.defpath
  1686. os.execv = mock_execv
  1687. os.execve = mock_execve
  1688. if defpath is not None:
  1689. os.defpath = defpath
  1690. yield calls
  1691. finally:
  1692. os.execv = orig_execv
  1693. os.execve = orig_execve
  1694. os.defpath = orig_defpath
  1695. @unittest.skipUnless(hasattr(os, 'execv'),
  1696. "need os.execv()")
  1697. class ExecTests(unittest.TestCase):
  1698. @unittest.skipIf(USING_LINUXTHREADS,
  1699. "avoid triggering a linuxthreads bug: see issue #4970")
  1700. def test_execvpe_with_bad_program(self):
  1701. self.assertRaises(OSError, os.execvpe, 'no such app-',
  1702. ['no such app-'], None)
  1703. def test_execv_with_bad_arglist(self):
  1704. self.assertRaises(ValueError, os.execv, 'notepad', ())
  1705. self.assertRaises(ValueError, os.execv, 'notepad', [])
  1706. self.assertRaises(ValueError, os.execv, 'notepad', ('',))
  1707. self.assertRaises(ValueError, os.execv, 'notepad', [''])
  1708. def test_execvpe_with_bad_arglist(self):
  1709. self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
  1710. self.assertRaises(ValueError, os.execvpe, 'notepad', [], {})
  1711. self.assertRaises(ValueError, os.execvpe, 'notepad', [''], {})
  1712. @unittest.skipUnless(hasattr(os, '_execvpe'),
  1713. "No internal os._execvpe function to test.")
  1714. def _test_internal_execvpe(self, test_type):
  1715. program_path = os.sep + 'absolutepath'
  1716. if test_type is bytes:
  1717. program = b'executable'
  1718. fullpath = os.path.join(os.fsencode(program_path), program)
  1719. native_fullpath = fullpath
  1720. arguments = [b'progname', 'arg1', 'arg2']
  1721. else:
  1722. program = 'executable'
  1723. arguments = ['progname', 'arg1', 'arg2']
  1724. fullpath = os.path.join(program_path, program)
  1725. if os.name != "nt":
  1726. native_fullpath = os.fsencode(fullpath)
  1727. else:
  1728. native_fullpath = fullpath
  1729. env = {'spam': 'beans'}
  1730. # test os._execvpe() with an absolute path
  1731. with _execvpe_mockup() as calls:
  1732. self.assertRaises(RuntimeError,
  1733. os._execvpe, fullpath, arguments)
  1734. self.assertEqual(len(calls), 1)
  1735. self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))
  1736. # test os._execvpe() with a relative path:
  1737. # os.get_exec_path() returns defpath
  1738. with _execvpe_mockup(defpath=program_path) as calls:
  1739. self.assertRaises(OSError,
  1740. os._execvpe, program, arguments, env=env)
  1741. self.assertEqual(len(calls), 1)
  1742. self.assertSequenceEqual(calls[0],
  1743. ('execve', native_fullpath, (arguments, env)))
  1744. # test os._execvpe() with a relative path:
  1745. # os.get_exec_path() reads the 'PATH' variable
  1746. with _execvpe_mockup() as calls:
  1747. env_path = env.copy()
  1748. if test_type is bytes:
  1749. env_path[b'PATH'] = program_path
  1750. else:
  1751. env_path['PATH'] = program_path
  1752. self.assertRaises(OSError,
  1753. os._execvpe, program, arguments, env=env_path)
  1754. self.assertEqual(len(calls), 1)
  1755. self.assertSequenceEqual(calls[0],
  1756. ('execve', native_fullpath, (arguments, env_path)))
  1757. def test_internal_execvpe_str(self):
  1758. self._test_internal_execvpe(str)
  1759. if os.name != "nt":
  1760. self._test_internal_execvpe(bytes)
  1761. def test_execve_invalid_env(self):
  1762. args = [sys.executable, '-c', 'pass']
  1763. # null character in the environment variable name
  1764. newenv = os.environ.copy()
  1765. newenv["FRUIT\0VEGETABLE"] = "cabbage"
  1766. with self.assertRaises(ValueError):
  1767. os.execve(args[0], args, newenv)
  1768. # null character in the environment variable value
  1769. newenv = os.environ.copy()
  1770. newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
  1771. with self.assertRaises(ValueError):
  1772. os.execve(args[0], args, newenv)
  1773. # equal character in the environment variable name
  1774. newenv = os.environ.copy()
  1775. newenv["FRUIT=ORANGE"] = "lemon"
  1776. with self.assertRaises(ValueError):
  1777. os.execve(args[0], args, newenv)
  1778. @unittest.skipUnless(sys.platform == "win32", "Win32-specific test")
  1779. def test_execve_with_empty_path(self):
  1780. # bpo-32890: Check GetLastError() misuse
  1781. try:
  1782. os.execve('', ['arg'], {})
  1783. except OSError as e:
  1784. self.assertTrue(e.winerror is None or e.winerror != 0)
  1785. else:
  1786. self.fail('No OSError raised')
  1787. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  1788. class Win32ErrorTests(unittest.TestCase):
  1789. def setUp(self):
  1790. try:
  1791. os.stat(os_helper.TESTFN)
  1792. except FileNotFoundError:
  1793. exists = False
  1794. except OSError as exc:
  1795. exists = True
  1796. self.fail("file %s must not exist; os.stat failed with %s"
  1797. % (os_helper.TESTFN, exc))
  1798. else:
  1799. self.fail("file %s must not exist" % os_helper.TESTFN)
  1800. def test_rename(self):
  1801. self.assertRaises(OSError, os.rename, os_helper.TESTFN, os_helper.TESTFN+".bak")
  1802. def test_remove(self):
  1803. self.assertRaises(OSError, os.remove, os_helper.TESTFN)
  1804. def test_chdir(self):
  1805. self.assertRaises(OSError, os.chdir, os_helper.TESTFN)
  1806. def test_mkdir(self):
  1807. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  1808. with open(os_helper.TESTFN, "x") as f:
  1809. self.assertRaises(OSError, os.mkdir, os_helper.TESTFN)
  1810. def test_utime(self):
  1811. self.assertRaises(OSError, os.utime, os_helper.TESTFN, None)
  1812. def test_chmod(self):
  1813. self.assertRaises(OSError, os.chmod, os_helper.TESTFN, 0)
  1814. @unittest.skipIf(support.is_wasi, "Cannot create invalid FD on WASI.")
  1815. class TestInvalidFD(unittest.TestCase):
  1816. singles = ["fchdir", "dup", "fdatasync", "fstat",
  1817. "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
  1818. #singles.append("close")
  1819. #We omit close because it doesn't raise an exception on some platforms
  1820. def get_single(f):
  1821. def helper(self):
  1822. if hasattr(os, f):
  1823. self.check(getattr(os, f))
  1824. return helper
  1825. for f in singles:
  1826. locals()["test_"+f] = get_single(f)
  1827. def check(self, f, *args, **kwargs):
  1828. try:
  1829. f(os_helper.make_bad_fd(), *args, **kwargs)
  1830. except OSError as e:
  1831. self.assertEqual(e.errno, errno.EBADF)
  1832. else:
  1833. self.fail("%r didn't raise an OSError with a bad file descriptor"
  1834. % f)
  1835. def test_fdopen(self):
  1836. self.check(os.fdopen, encoding="utf-8")
  1837. @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
  1838. def test_isatty(self):
  1839. self.assertEqual(os.isatty(os_helper.make_bad_fd()), False)
  1840. @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()')
  1841. def test_closerange(self):
  1842. fd = os_helper.make_bad_fd()
  1843. # Make sure none of the descriptors we are about to close are
  1844. # currently valid (issue 6542).
  1845. for i in range(10):
  1846. try: os.fstat(fd+i)
  1847. except OSError:
  1848. pass
  1849. else:
  1850. break
  1851. if i < 2:
  1852. raise unittest.SkipTest(
  1853. "Unable to acquire a range of invalid file descriptors")
  1854. self.assertEqual(os.closerange(fd, fd + i-1), None)
  1855. @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
  1856. def test_dup2(self):
  1857. self.check(os.dup2, 20)
  1858. @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
  1859. def test_fchmod(self):
  1860. self.check(os.fchmod, 0)
  1861. @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()')
  1862. def test_fchown(self):
  1863. self.check(os.fchown, -1, -1)
  1864. @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()')
  1865. @unittest.skipIf(
  1866. support.is_emscripten or support.is_wasi,
  1867. "musl libc issue on Emscripten/WASI, bpo-46390"
  1868. )
  1869. def test_fpathconf(self):
  1870. self.check(os.pathconf, "PC_NAME_MAX")
  1871. self.check(os.fpathconf, "PC_NAME_MAX")
  1872. @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
  1873. def test_ftruncate(self):
  1874. self.check(os.truncate, 0)
  1875. self.check(os.ftruncate, 0)
  1876. @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
  1877. def test_lseek(self):
  1878. self.check(os.lseek, 0, 0)
  1879. @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()')
  1880. def test_read(self):
  1881. self.check(os.read, 1)
  1882. @unittest.skipUnless(hasattr(os, 'readv'), 'test needs os.readv()')
  1883. def test_readv(self):
  1884. buf = bytearray(10)
  1885. self.check(os.readv, [buf])
  1886. @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()')
  1887. def test_tcsetpgrpt(self):
  1888. self.check(os.tcsetpgrp, 0)
  1889. @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()')
  1890. def test_write(self):
  1891. self.check(os.write, b" ")
  1892. @unittest.skipUnless(hasattr(os, 'writev'), 'test needs os.writev()')
  1893. def test_writev(self):
  1894. self.check(os.writev, [b'abc'])
  1895. @support.requires_subprocess()
  1896. def test_inheritable(self):
  1897. self.check(os.get_inheritable)
  1898. self.check(os.set_inheritable, True)
  1899. @unittest.skipUnless(hasattr(os, 'get_blocking'),
  1900. 'needs os.get_blocking() and os.set_blocking()')
  1901. def test_blocking(self):
  1902. self.check(os.get_blocking)
  1903. self.check(os.set_blocking, True)
  1904. @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
  1905. class LinkTests(unittest.TestCase):
  1906. def setUp(self):
  1907. self.file1 = os_helper.TESTFN
  1908. self.file2 = os.path.join(os_helper.TESTFN + "2")
  1909. def tearDown(self):
  1910. for file in (self.file1, self.file2):
  1911. if os.path.exists(file):
  1912. os.unlink(file)
  1913. def _test_link(self, file1, file2):
  1914. create_file(file1)
  1915. try:
  1916. os.link(file1, file2)
  1917. except PermissionError as e:
  1918. self.skipTest('os.link(): %s' % e)
  1919. with open(file1, "rb") as f1, open(file2, "rb") as f2:
  1920. self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
  1921. def test_link(self):
  1922. self._test_link(self.file1, self.file2)
  1923. def test_link_bytes(self):
  1924. self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
  1925. bytes(self.file2, sys.getfilesystemencoding()))
  1926. def test_unicode_name(self):
  1927. try:
  1928. os.fsencode("\xf1")
  1929. except UnicodeError:
  1930. raise unittest.SkipTest("Unable to encode for this platform.")
  1931. self.file1 += "\xf1"
  1932. self.file2 = self.file1 + "2"
  1933. self._test_link(self.file1, self.file2)
  1934. @unittest.skipIf(sys.platform == "win32", "Posix specific tests")
  1935. class PosixUidGidTests(unittest.TestCase):
  1936. # uid_t and gid_t are 32-bit unsigned integers on Linux
  1937. UID_OVERFLOW = (1 << 32)
  1938. GID_OVERFLOW = (1 << 32)
  1939. @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()')
  1940. def test_setuid(self):
  1941. if os.getuid() != 0:
  1942. self.assertRaises(OSError, os.setuid, 0)
  1943. self.assertRaises(TypeError, os.setuid, 'not an int')
  1944. self.assertRaises(OverflowError, os.setuid, self.UID_OVERFLOW)
  1945. @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()')
  1946. def test_setgid(self):
  1947. if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
  1948. self.assertRaises(OSError, os.setgid, 0)
  1949. self.assertRaises(TypeError, os.setgid, 'not an int')
  1950. self.assertRaises(OverflowError, os.setgid, self.GID_OVERFLOW)
  1951. @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()')
  1952. def test_seteuid(self):
  1953. if os.getuid() != 0:
  1954. self.assertRaises(OSError, os.seteuid, 0)
  1955. self.assertRaises(TypeError, os.setegid, 'not an int')
  1956. self.assertRaises(OverflowError, os.seteuid, self.UID_OVERFLOW)
  1957. @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()')
  1958. def test_setegid(self):
  1959. if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
  1960. self.assertRaises(OSError, os.setegid, 0)
  1961. self.assertRaises(TypeError, os.setegid, 'not an int')
  1962. self.assertRaises(OverflowError, os.setegid, self.GID_OVERFLOW)
  1963. @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
  1964. def test_setreuid(self):
  1965. if os.getuid() != 0:
  1966. self.assertRaises(OSError, os.setreuid, 0, 0)
  1967. self.assertRaises(TypeError, os.setreuid, 'not an int', 0)
  1968. self.assertRaises(TypeError, os.setreuid, 0, 'not an int')
  1969. self.assertRaises(OverflowError, os.setreuid, self.UID_OVERFLOW, 0)
  1970. self.assertRaises(OverflowError, os.setreuid, 0, self.UID_OVERFLOW)
  1971. @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()')
  1972. @support.requires_subprocess()
  1973. def test_setreuid_neg1(self):
  1974. # Needs to accept -1. We run this in a subprocess to avoid
  1975. # altering the test runner's process state (issue8045).
  1976. subprocess.check_call([
  1977. sys.executable, '-c',
  1978. 'import os,sys;os.setreuid(-1,-1);sys.exit(0)'])
  1979. @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
  1980. @support.requires_subprocess()
  1981. def test_setregid(self):
  1982. if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
  1983. self.assertRaises(OSError, os.setregid, 0, 0)
  1984. self.assertRaises(TypeError, os.setregid, 'not an int', 0)
  1985. self.assertRaises(TypeError, os.setregid, 0, 'not an int')
  1986. self.assertRaises(OverflowError, os.setregid, self.GID_OVERFLOW, 0)
  1987. self.assertRaises(OverflowError, os.setregid, 0, self.GID_OVERFLOW)
  1988. @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()')
  1989. @support.requires_subprocess()
  1990. def test_setregid_neg1(self):
  1991. # Needs to accept -1. We run this in a subprocess to avoid
  1992. # altering the test runner's process state (issue8045).
  1993. subprocess.check_call([
  1994. sys.executable, '-c',
  1995. 'import os,sys;os.setregid(-1,-1);sys.exit(0)'])
  1996. @unittest.skipIf(sys.platform == "win32", "Posix specific tests")
  1997. class Pep383Tests(unittest.TestCase):
  1998. def setUp(self):
  1999. if os_helper.TESTFN_UNENCODABLE:
  2000. self.dir = os_helper.TESTFN_UNENCODABLE
  2001. elif os_helper.TESTFN_NONASCII:
  2002. self.dir = os_helper.TESTFN_NONASCII
  2003. else:
  2004. self.dir = os_helper.TESTFN
  2005. self.bdir = os.fsencode(self.dir)
  2006. bytesfn = []
  2007. def add_filename(fn):
  2008. try:
  2009. fn = os.fsencode(fn)
  2010. except UnicodeEncodeError:
  2011. return
  2012. bytesfn.append(fn)
  2013. add_filename(os_helper.TESTFN_UNICODE)
  2014. if os_helper.TESTFN_UNENCODABLE:
  2015. add_filename(os_helper.TESTFN_UNENCODABLE)
  2016. if os_helper.TESTFN_NONASCII:
  2017. add_filename(os_helper.TESTFN_NONASCII)
  2018. if not bytesfn:
  2019. self.skipTest("couldn't create any non-ascii filename")
  2020. self.unicodefn = set()
  2021. os.mkdir(self.dir)
  2022. try:
  2023. for fn in bytesfn:
  2024. os_helper.create_empty_file(os.path.join(self.bdir, fn))
  2025. fn = os.fsdecode(fn)
  2026. if fn in self.unicodefn:
  2027. raise ValueError("duplicate filename")
  2028. self.unicodefn.add(fn)
  2029. except:
  2030. shutil.rmtree(self.dir)
  2031. raise
  2032. def tearDown(self):
  2033. shutil.rmtree(self.dir)
  2034. def test_listdir(self):
  2035. expected = self.unicodefn
  2036. found = set(os.listdir(self.dir))
  2037. self.assertEqual(found, expected)
  2038. # test listdir without arguments
  2039. current_directory = os.getcwd()
  2040. try:
  2041. os.chdir(os.sep)
  2042. self.assertEqual(set(os.listdir()), set(os.listdir(os.sep)))
  2043. finally:
  2044. os.chdir(current_directory)
  2045. def test_open(self):
  2046. for fn in self.unicodefn:
  2047. f = open(os.path.join(self.dir, fn), 'rb')
  2048. f.close()
  2049. @unittest.skipUnless(hasattr(os, 'statvfs'),
  2050. "need os.statvfs()")
  2051. def test_statvfs(self):
  2052. # issue #9645
  2053. for fn in self.unicodefn:
  2054. # should not fail with file not found error
  2055. fullname = os.path.join(self.dir, fn)
  2056. os.statvfs(fullname)
  2057. def test_stat(self):
  2058. for fn in self.unicodefn:
  2059. os.stat(os.path.join(self.dir, fn))
  2060. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  2061. class Win32KillTests(unittest.TestCase):
  2062. def _kill(self, sig):
  2063. # Start sys.executable as a subprocess and communicate from the
  2064. # subprocess to the parent that the interpreter is ready. When it
  2065. # becomes ready, send *sig* via os.kill to the subprocess and check
  2066. # that the return code is equal to *sig*.
  2067. import ctypes
  2068. from ctypes import wintypes
  2069. import msvcrt
  2070. # Since we can't access the contents of the process' stdout until the
  2071. # process has exited, use PeekNamedPipe to see what's inside stdout
  2072. # without waiting. This is done so we can tell that the interpreter
  2073. # is started and running at a point where it could handle a signal.
  2074. PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
  2075. PeekNamedPipe.restype = wintypes.BOOL
  2076. PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
  2077. ctypes.POINTER(ctypes.c_char), # stdout buf
  2078. wintypes.DWORD, # Buffer size
  2079. ctypes.POINTER(wintypes.DWORD), # bytes read
  2080. ctypes.POINTER(wintypes.DWORD), # bytes avail
  2081. ctypes.POINTER(wintypes.DWORD)) # bytes left
  2082. msg = "running"
  2083. proc = subprocess.Popen([sys.executable, "-c",
  2084. "import sys;"
  2085. "sys.stdout.write('{}');"
  2086. "sys.stdout.flush();"
  2087. "input()".format(msg)],
  2088. stdout=subprocess.PIPE,
  2089. stderr=subprocess.PIPE,
  2090. stdin=subprocess.PIPE)
  2091. self.addCleanup(proc.stdout.close)
  2092. self.addCleanup(proc.stderr.close)
  2093. self.addCleanup(proc.stdin.close)
  2094. count, max = 0, 100
  2095. while count < max and proc.poll() is None:
  2096. # Create a string buffer to store the result of stdout from the pipe
  2097. buf = ctypes.create_string_buffer(len(msg))
  2098. # Obtain the text currently in proc.stdout
  2099. # Bytes read/avail/left are left as NULL and unused
  2100. rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
  2101. buf, ctypes.sizeof(buf), None, None, None)
  2102. self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
  2103. if buf.value:
  2104. self.assertEqual(msg, buf.value.decode())
  2105. break
  2106. time.sleep(0.1)
  2107. count += 1
  2108. else:
  2109. self.fail("Did not receive communication from the subprocess")
  2110. os.kill(proc.pid, sig)
  2111. self.assertEqual(proc.wait(), sig)
  2112. def test_kill_sigterm(self):
  2113. # SIGTERM doesn't mean anything special, but make sure it works
  2114. self._kill(signal.SIGTERM)
  2115. def test_kill_int(self):
  2116. # os.kill on Windows can take an int which gets set as the exit code
  2117. self._kill(100)
  2118. @unittest.skipIf(mmap is None, "requires mmap")
  2119. def _kill_with_event(self, event, name):
  2120. tagname = "test_os_%s" % uuid.uuid1()
  2121. m = mmap.mmap(-1, 1, tagname)
  2122. m[0] = 0
  2123. # Run a script which has console control handling enabled.
  2124. proc = subprocess.Popen([sys.executable,
  2125. os.path.join(os.path.dirname(__file__),
  2126. "win_console_handler.py"), tagname],
  2127. creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
  2128. # Let the interpreter startup before we send signals. See #3137.
  2129. count, max = 0, 100
  2130. while count < max and proc.poll() is None:
  2131. if m[0] == 1:
  2132. break
  2133. time.sleep(0.1)
  2134. count += 1
  2135. else:
  2136. # Forcefully kill the process if we weren't able to signal it.
  2137. os.kill(proc.pid, signal.SIGINT)
  2138. self.fail("Subprocess didn't finish initialization")
  2139. os.kill(proc.pid, event)
  2140. # proc.send_signal(event) could also be done here.
  2141. # Allow time for the signal to be passed and the process to exit.
  2142. time.sleep(0.5)
  2143. if not proc.poll():
  2144. # Forcefully kill the process if we weren't able to signal it.
  2145. os.kill(proc.pid, signal.SIGINT)
  2146. self.fail("subprocess did not stop on {}".format(name))
  2147. @unittest.skip("subprocesses aren't inheriting Ctrl+C property")
  2148. @support.requires_subprocess()
  2149. def test_CTRL_C_EVENT(self):
  2150. from ctypes import wintypes
  2151. import ctypes
  2152. # Make a NULL value by creating a pointer with no argument.
  2153. NULL = ctypes.POINTER(ctypes.c_int)()
  2154. SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler
  2155. SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int),
  2156. wintypes.BOOL)
  2157. SetConsoleCtrlHandler.restype = wintypes.BOOL
  2158. # Calling this with NULL and FALSE causes the calling process to
  2159. # handle Ctrl+C, rather than ignore it. This property is inherited
  2160. # by subprocesses.
  2161. SetConsoleCtrlHandler(NULL, 0)
  2162. self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT")
  2163. @support.requires_subprocess()
  2164. def test_CTRL_BREAK_EVENT(self):
  2165. self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
  2166. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  2167. class Win32ListdirTests(unittest.TestCase):
  2168. """Test listdir on Windows."""
  2169. def setUp(self):
  2170. self.created_paths = []
  2171. for i in range(2):
  2172. dir_name = 'SUB%d' % i
  2173. dir_path = os.path.join(os_helper.TESTFN, dir_name)
  2174. file_name = 'FILE%d' % i
  2175. file_path = os.path.join(os_helper.TESTFN, file_name)
  2176. os.makedirs(dir_path)
  2177. with open(file_path, 'w', encoding='utf-8') as f:
  2178. f.write("I'm %s and proud of it. Blame test_os.\n" % file_path)
  2179. self.created_paths.extend([dir_name, file_name])
  2180. self.created_paths.sort()
  2181. def tearDown(self):
  2182. shutil.rmtree(os_helper.TESTFN)
  2183. def test_listdir_no_extended_path(self):
  2184. """Test when the path is not an "extended" path."""
  2185. # unicode
  2186. self.assertEqual(
  2187. sorted(os.listdir(os_helper.TESTFN)),
  2188. self.created_paths)
  2189. # bytes
  2190. self.assertEqual(
  2191. sorted(os.listdir(os.fsencode(os_helper.TESTFN))),
  2192. [os.fsencode(path) for path in self.created_paths])
  2193. def test_listdir_extended_path(self):
  2194. """Test when the path starts with '\\\\?\\'."""
  2195. # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
  2196. # unicode
  2197. path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN)
  2198. self.assertEqual(
  2199. sorted(os.listdir(path)),
  2200. self.created_paths)
  2201. # bytes
  2202. path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN))
  2203. self.assertEqual(
  2204. sorted(os.listdir(path)),
  2205. [os.fsencode(path) for path in self.created_paths])
  2206. @unittest.skipUnless(hasattr(os, 'readlink'), 'needs os.readlink()')
  2207. class ReadlinkTests(unittest.TestCase):
  2208. filelink = 'readlinktest'
  2209. filelink_target = os.path.abspath(__file__)
  2210. filelinkb = os.fsencode(filelink)
  2211. filelinkb_target = os.fsencode(filelink_target)
  2212. def assertPathEqual(self, left, right):
  2213. left = os.path.normcase(left)
  2214. right = os.path.normcase(right)
  2215. if sys.platform == 'win32':
  2216. # Bad practice to blindly strip the prefix as it may be required to
  2217. # correctly refer to the file, but we're only comparing paths here.
  2218. has_prefix = lambda p: p.startswith(
  2219. b'\\\\?\\' if isinstance(p, bytes) else '\\\\?\\')
  2220. if has_prefix(left):
  2221. left = left[4:]
  2222. if has_prefix(right):
  2223. right = right[4:]
  2224. self.assertEqual(left, right)
  2225. def setUp(self):
  2226. self.assertTrue(os.path.exists(self.filelink_target))
  2227. self.assertTrue(os.path.exists(self.filelinkb_target))
  2228. self.assertFalse(os.path.exists(self.filelink))
  2229. self.assertFalse(os.path.exists(self.filelinkb))
  2230. def test_not_symlink(self):
  2231. filelink_target = FakePath(self.filelink_target)
  2232. self.assertRaises(OSError, os.readlink, self.filelink_target)
  2233. self.assertRaises(OSError, os.readlink, filelink_target)
  2234. def test_missing_link(self):
  2235. self.assertRaises(FileNotFoundError, os.readlink, 'missing-link')
  2236. self.assertRaises(FileNotFoundError, os.readlink,
  2237. FakePath('missing-link'))
  2238. @os_helper.skip_unless_symlink
  2239. def test_pathlike(self):
  2240. os.symlink(self.filelink_target, self.filelink)
  2241. self.addCleanup(os_helper.unlink, self.filelink)
  2242. filelink = FakePath(self.filelink)
  2243. self.assertPathEqual(os.readlink(filelink), self.filelink_target)
  2244. @os_helper.skip_unless_symlink
  2245. def test_pathlike_bytes(self):
  2246. os.symlink(self.filelinkb_target, self.filelinkb)
  2247. self.addCleanup(os_helper.unlink, self.filelinkb)
  2248. path = os.readlink(FakePath(self.filelinkb))
  2249. self.assertPathEqual(path, self.filelinkb_target)
  2250. self.assertIsInstance(path, bytes)
  2251. @os_helper.skip_unless_symlink
  2252. def test_bytes(self):
  2253. os.symlink(self.filelinkb_target, self.filelinkb)
  2254. self.addCleanup(os_helper.unlink, self.filelinkb)
  2255. path = os.readlink(self.filelinkb)
  2256. self.assertPathEqual(path, self.filelinkb_target)
  2257. self.assertIsInstance(path, bytes)
  2258. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  2259. @os_helper.skip_unless_symlink
  2260. class Win32SymlinkTests(unittest.TestCase):
  2261. filelink = 'filelinktest'
  2262. filelink_target = os.path.abspath(__file__)
  2263. dirlink = 'dirlinktest'
  2264. dirlink_target = os.path.dirname(filelink_target)
  2265. missing_link = 'missing link'
  2266. def setUp(self):
  2267. assert os.path.exists(self.dirlink_target)
  2268. assert os.path.exists(self.filelink_target)
  2269. assert not os.path.exists(self.dirlink)
  2270. assert not os.path.exists(self.filelink)
  2271. assert not os.path.exists(self.missing_link)
  2272. def tearDown(self):
  2273. if os.path.exists(self.filelink):
  2274. os.remove(self.filelink)
  2275. if os.path.exists(self.dirlink):
  2276. os.rmdir(self.dirlink)
  2277. if os.path.lexists(self.missing_link):
  2278. os.remove(self.missing_link)
  2279. def test_directory_link(self):
  2280. os.symlink(self.dirlink_target, self.dirlink)
  2281. self.assertTrue(os.path.exists(self.dirlink))
  2282. self.assertTrue(os.path.isdir(self.dirlink))
  2283. self.assertTrue(os.path.islink(self.dirlink))
  2284. self.check_stat(self.dirlink, self.dirlink_target)
  2285. def test_file_link(self):
  2286. os.symlink(self.filelink_target, self.filelink)
  2287. self.assertTrue(os.path.exists(self.filelink))
  2288. self.assertTrue(os.path.isfile(self.filelink))
  2289. self.assertTrue(os.path.islink(self.filelink))
  2290. self.check_stat(self.filelink, self.filelink_target)
  2291. def _create_missing_dir_link(self):
  2292. 'Create a "directory" link to a non-existent target'
  2293. linkname = self.missing_link
  2294. if os.path.lexists(linkname):
  2295. os.remove(linkname)
  2296. target = r'c:\\target does not exist.29r3c740'
  2297. assert not os.path.exists(target)
  2298. target_is_dir = True
  2299. os.symlink(target, linkname, target_is_dir)
  2300. def test_remove_directory_link_to_missing_target(self):
  2301. self._create_missing_dir_link()
  2302. # For compatibility with Unix, os.remove will check the
  2303. # directory status and call RemoveDirectory if the symlink
  2304. # was created with target_is_dir==True.
  2305. os.remove(self.missing_link)
  2306. def test_isdir_on_directory_link_to_missing_target(self):
  2307. self._create_missing_dir_link()
  2308. self.assertFalse(os.path.isdir(self.missing_link))
  2309. def test_rmdir_on_directory_link_to_missing_target(self):
  2310. self._create_missing_dir_link()
  2311. os.rmdir(self.missing_link)
  2312. def check_stat(self, link, target):
  2313. self.assertEqual(os.stat(link), os.stat(target))
  2314. self.assertNotEqual(os.lstat(link), os.stat(link))
  2315. bytes_link = os.fsencode(link)
  2316. self.assertEqual(os.stat(bytes_link), os.stat(target))
  2317. self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link))
  2318. def test_12084(self):
  2319. level1 = os.path.abspath(os_helper.TESTFN)
  2320. level2 = os.path.join(level1, "level2")
  2321. level3 = os.path.join(level2, "level3")
  2322. self.addCleanup(os_helper.rmtree, level1)
  2323. os.mkdir(level1)
  2324. os.mkdir(level2)
  2325. os.mkdir(level3)
  2326. file1 = os.path.abspath(os.path.join(level1, "file1"))
  2327. create_file(file1)
  2328. orig_dir = os.getcwd()
  2329. try:
  2330. os.chdir(level2)
  2331. link = os.path.join(level2, "link")
  2332. os.symlink(os.path.relpath(file1), "link")
  2333. self.assertIn("link", os.listdir(os.getcwd()))
  2334. # Check os.stat calls from the same dir as the link
  2335. self.assertEqual(os.stat(file1), os.stat("link"))
  2336. # Check os.stat calls from a dir below the link
  2337. os.chdir(level1)
  2338. self.assertEqual(os.stat(file1),
  2339. os.stat(os.path.relpath(link)))
  2340. # Check os.stat calls from a dir above the link
  2341. os.chdir(level3)
  2342. self.assertEqual(os.stat(file1),
  2343. os.stat(os.path.relpath(link)))
  2344. finally:
  2345. os.chdir(orig_dir)
  2346. @unittest.skipUnless(os.path.lexists(r'C:\Users\All Users')
  2347. and os.path.exists(r'C:\ProgramData'),
  2348. 'Test directories not found')
  2349. def test_29248(self):
  2350. # os.symlink() calls CreateSymbolicLink, which creates
  2351. # the reparse data buffer with the print name stored
  2352. # first, so the offset is always 0. CreateSymbolicLink
  2353. # stores the "PrintName" DOS path (e.g. "C:\") first,
  2354. # with an offset of 0, followed by the "SubstituteName"
  2355. # NT path (e.g. "\??\C:\"). The "All Users" link, on
  2356. # the other hand, seems to have been created manually
  2357. # with an inverted order.
  2358. target = os.readlink(r'C:\Users\All Users')
  2359. self.assertTrue(os.path.samefile(target, r'C:\ProgramData'))
  2360. def test_buffer_overflow(self):
  2361. # Older versions would have a buffer overflow when detecting
  2362. # whether a link source was a directory. This test ensures we
  2363. # no longer crash, but does not otherwise validate the behavior
  2364. segment = 'X' * 27
  2365. path = os.path.join(*[segment] * 10)
  2366. test_cases = [
  2367. # overflow with absolute src
  2368. ('\\' + path, segment),
  2369. # overflow dest with relative src
  2370. (segment, path),
  2371. # overflow when joining src
  2372. (path[:180], path[:180]),
  2373. ]
  2374. for src, dest in test_cases:
  2375. try:
  2376. os.symlink(src, dest)
  2377. except FileNotFoundError:
  2378. pass
  2379. else:
  2380. try:
  2381. os.remove(dest)
  2382. except OSError:
  2383. pass
  2384. # Also test with bytes, since that is a separate code path.
  2385. try:
  2386. os.symlink(os.fsencode(src), os.fsencode(dest))
  2387. except FileNotFoundError:
  2388. pass
  2389. else:
  2390. try:
  2391. os.remove(dest)
  2392. except OSError:
  2393. pass
  2394. def test_appexeclink(self):
  2395. root = os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\WindowsApps')
  2396. if not os.path.isdir(root):
  2397. self.skipTest("test requires a WindowsApps directory")
  2398. aliases = [os.path.join(root, a)
  2399. for a in fnmatch.filter(os.listdir(root), '*.exe')]
  2400. for alias in aliases:
  2401. if support.verbose:
  2402. print()
  2403. print("Testing with", alias)
  2404. st = os.lstat(alias)
  2405. self.assertEqual(st, os.stat(alias))
  2406. self.assertFalse(stat.S_ISLNK(st.st_mode))
  2407. self.assertEqual(st.st_reparse_tag, stat.IO_REPARSE_TAG_APPEXECLINK)
  2408. # testing the first one we see is sufficient
  2409. break
  2410. else:
  2411. self.skipTest("test requires an app execution alias")
  2412. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  2413. class Win32JunctionTests(unittest.TestCase):
  2414. junction = 'junctiontest'
  2415. junction_target = os.path.dirname(os.path.abspath(__file__))
  2416. def setUp(self):
  2417. assert os.path.exists(self.junction_target)
  2418. assert not os.path.lexists(self.junction)
  2419. def tearDown(self):
  2420. if os.path.lexists(self.junction):
  2421. os.unlink(self.junction)
  2422. def test_create_junction(self):
  2423. _winapi.CreateJunction(self.junction_target, self.junction)
  2424. self.assertTrue(os.path.lexists(self.junction))
  2425. self.assertTrue(os.path.exists(self.junction))
  2426. self.assertTrue(os.path.isdir(self.junction))
  2427. self.assertNotEqual(os.stat(self.junction), os.lstat(self.junction))
  2428. self.assertEqual(os.stat(self.junction), os.stat(self.junction_target))
  2429. # bpo-37834: Junctions are not recognized as links.
  2430. self.assertFalse(os.path.islink(self.junction))
  2431. self.assertEqual(os.path.normcase("\\\\?\\" + self.junction_target),
  2432. os.path.normcase(os.readlink(self.junction)))
  2433. def test_unlink_removes_junction(self):
  2434. _winapi.CreateJunction(self.junction_target, self.junction)
  2435. self.assertTrue(os.path.exists(self.junction))
  2436. self.assertTrue(os.path.lexists(self.junction))
  2437. os.unlink(self.junction)
  2438. self.assertFalse(os.path.exists(self.junction))
  2439. @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
  2440. class Win32NtTests(unittest.TestCase):
  2441. def test_getfinalpathname_handles(self):
  2442. nt = import_helper.import_module('nt')
  2443. ctypes = import_helper.import_module('ctypes')
  2444. import ctypes.wintypes
  2445. kernel = ctypes.WinDLL('Kernel32.dll', use_last_error=True)
  2446. kernel.GetCurrentProcess.restype = ctypes.wintypes.HANDLE
  2447. kernel.GetProcessHandleCount.restype = ctypes.wintypes.BOOL
  2448. kernel.GetProcessHandleCount.argtypes = (ctypes.wintypes.HANDLE,
  2449. ctypes.wintypes.LPDWORD)
  2450. # This is a pseudo-handle that doesn't need to be closed
  2451. hproc = kernel.GetCurrentProcess()
  2452. handle_count = ctypes.wintypes.DWORD()
  2453. ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count))
  2454. self.assertEqual(1, ok)
  2455. before_count = handle_count.value
  2456. # The first two test the error path, __file__ tests the success path
  2457. filenames = [
  2458. r'\\?\C:',
  2459. r'\\?\NUL',
  2460. r'\\?\CONIN',
  2461. __file__,
  2462. ]
  2463. for _ in range(10):
  2464. for name in filenames:
  2465. try:
  2466. nt._getfinalpathname(name)
  2467. except Exception:
  2468. # Failure is expected
  2469. pass
  2470. try:
  2471. os.stat(name)
  2472. except Exception:
  2473. pass
  2474. ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count))
  2475. self.assertEqual(1, ok)
  2476. handle_delta = handle_count.value - before_count
  2477. self.assertEqual(0, handle_delta)
  2478. @support.requires_subprocess()
  2479. def test_stat_unlink_race(self):
  2480. # bpo-46785: the implementation of os.stat() falls back to reading
  2481. # the parent directory if CreateFileW() fails with a permission
  2482. # error. If reading the parent directory fails because the file or
  2483. # directory are subsequently unlinked, or because the volume or
  2484. # share are no longer available, then the original permission error
  2485. # should not be restored.
  2486. filename = os_helper.TESTFN
  2487. self.addCleanup(os_helper.unlink, filename)
  2488. deadline = time.time() + 5
  2489. command = textwrap.dedent("""\
  2490. import os
  2491. import sys
  2492. import time
  2493. filename = sys.argv[1]
  2494. deadline = float(sys.argv[2])
  2495. while time.time() < deadline:
  2496. try:
  2497. with open(filename, "w") as f:
  2498. pass
  2499. except OSError:
  2500. pass
  2501. try:
  2502. os.remove(filename)
  2503. except OSError:
  2504. pass
  2505. """)
  2506. with subprocess.Popen([sys.executable, '-c', command, filename, str(deadline)]) as proc:
  2507. while time.time() < deadline:
  2508. try:
  2509. os.stat(filename)
  2510. except FileNotFoundError as e:
  2511. assert e.winerror == 2 # ERROR_FILE_NOT_FOUND
  2512. try:
  2513. proc.wait(1)
  2514. except subprocess.TimeoutExpired:
  2515. proc.terminate()
  2516. @os_helper.skip_unless_symlink
  2517. class NonLocalSymlinkTests(unittest.TestCase):
  2518. def setUp(self):
  2519. r"""
  2520. Create this structure:
  2521. base
  2522. \___ some_dir
  2523. """
  2524. os.makedirs('base/some_dir')
  2525. def tearDown(self):
  2526. shutil.rmtree('base')
  2527. def test_directory_link_nonlocal(self):
  2528. """
  2529. The symlink target should resolve relative to the link, not relative
  2530. to the current directory.
  2531. Then, link base/some_link -> base/some_dir and ensure that some_link
  2532. is resolved as a directory.
  2533. In issue13772, it was discovered that directory detection failed if
  2534. the symlink target was not specified relative to the current
  2535. directory, which was a defect in the implementation.
  2536. """
  2537. src = os.path.join('base', 'some_link')
  2538. os.symlink('some_dir', src)
  2539. assert os.path.isdir(src)
  2540. class FSEncodingTests(unittest.TestCase):
  2541. def test_nop(self):
  2542. self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
  2543. self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
  2544. def test_identity(self):
  2545. # assert fsdecode(fsencode(x)) == x
  2546. for fn in ('unicode\u0141', 'latin\xe9', 'ascii'):
  2547. try:
  2548. bytesfn = os.fsencode(fn)
  2549. except UnicodeEncodeError:
  2550. continue
  2551. self.assertEqual(os.fsdecode(bytesfn), fn)
  2552. class DeviceEncodingTests(unittest.TestCase):
  2553. def test_bad_fd(self):
  2554. # Return None when an fd doesn't actually exist.
  2555. self.assertIsNone(os.device_encoding(123456))
  2556. @unittest.skipUnless(os.isatty(0) and not win32_is_iot() and (sys.platform.startswith('win') or
  2557. (hasattr(locale, 'nl_langinfo') and hasattr(locale, 'CODESET'))),
  2558. 'test requires a tty and either Windows or nl_langinfo(CODESET)')
  2559. @unittest.skipIf(
  2560. support.is_emscripten, "Cannot get encoding of stdin on Emscripten"
  2561. )
  2562. def test_device_encoding(self):
  2563. encoding = os.device_encoding(0)
  2564. self.assertIsNotNone(encoding)
  2565. self.assertTrue(codecs.lookup(encoding))
  2566. @support.requires_subprocess()
  2567. class PidTests(unittest.TestCase):
  2568. @unittest.skipUnless(hasattr(os, 'getppid'), "test needs os.getppid")
  2569. def test_getppid(self):
  2570. p = subprocess.Popen([sys.executable, '-c',
  2571. 'import os; print(os.getppid())'],
  2572. stdout=subprocess.PIPE)
  2573. stdout, _ = p.communicate()
  2574. # We are the parent of our subprocess
  2575. self.assertEqual(int(stdout), os.getpid())
  2576. def check_waitpid(self, code, exitcode, callback=None):
  2577. if sys.platform == 'win32':
  2578. # On Windows, os.spawnv() simply joins arguments with spaces:
  2579. # arguments need to be quoted
  2580. args = [f'"{sys.executable}"', '-c', f'"{code}"']
  2581. else:
  2582. args = [sys.executable, '-c', code]
  2583. pid = os.spawnv(os.P_NOWAIT, sys.executable, args)
  2584. if callback is not None:
  2585. callback(pid)
  2586. # don't use support.wait_process() to test directly os.waitpid()
  2587. # and os.waitstatus_to_exitcode()
  2588. pid2, status = os.waitpid(pid, 0)
  2589. self.assertEqual(os.waitstatus_to_exitcode(status), exitcode)
  2590. self.assertEqual(pid2, pid)
  2591. def test_waitpid(self):
  2592. self.check_waitpid(code='pass', exitcode=0)
  2593. def test_waitstatus_to_exitcode(self):
  2594. exitcode = 23
  2595. code = f'import sys; sys.exit({exitcode})'
  2596. self.check_waitpid(code, exitcode=exitcode)
  2597. with self.assertRaises(TypeError):
  2598. os.waitstatus_to_exitcode(0.0)
  2599. @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
  2600. def test_waitpid_windows(self):
  2601. # bpo-40138: test os.waitpid() and os.waitstatus_to_exitcode()
  2602. # with exit code larger than INT_MAX.
  2603. STATUS_CONTROL_C_EXIT = 0xC000013A
  2604. code = f'import _winapi; _winapi.ExitProcess({STATUS_CONTROL_C_EXIT})'
  2605. self.check_waitpid(code, exitcode=STATUS_CONTROL_C_EXIT)
  2606. @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
  2607. def test_waitstatus_to_exitcode_windows(self):
  2608. max_exitcode = 2 ** 32 - 1
  2609. for exitcode in (0, 1, 5, max_exitcode):
  2610. self.assertEqual(os.waitstatus_to_exitcode(exitcode << 8),
  2611. exitcode)
  2612. # invalid values
  2613. with self.assertRaises(ValueError):
  2614. os.waitstatus_to_exitcode((max_exitcode + 1) << 8)
  2615. with self.assertRaises(OverflowError):
  2616. os.waitstatus_to_exitcode(-1)
  2617. # Skip the test on Windows
  2618. @unittest.skipUnless(hasattr(signal, 'SIGKILL'), 'need signal.SIGKILL')
  2619. def test_waitstatus_to_exitcode_kill(self):
  2620. code = f'import time; time.sleep({support.LONG_TIMEOUT})'
  2621. signum = signal.SIGKILL
  2622. def kill_process(pid):
  2623. os.kill(pid, signum)
  2624. self.check_waitpid(code, exitcode=-signum, callback=kill_process)
  2625. @support.requires_subprocess()
  2626. class SpawnTests(unittest.TestCase):
  2627. def create_args(self, *, with_env=False, use_bytes=False):
  2628. self.exitcode = 17
  2629. filename = os_helper.TESTFN
  2630. self.addCleanup(os_helper.unlink, filename)
  2631. if not with_env:
  2632. code = 'import sys; sys.exit(%s)' % self.exitcode
  2633. else:
  2634. self.env = dict(os.environ)
  2635. # create an unique key
  2636. self.key = str(uuid.uuid4())
  2637. self.env[self.key] = self.key
  2638. # read the variable from os.environ to check that it exists
  2639. code = ('import sys, os; magic = os.environ[%r]; sys.exit(%s)'
  2640. % (self.key, self.exitcode))
  2641. with open(filename, "w", encoding="utf-8") as fp:
  2642. fp.write(code)
  2643. args = [sys.executable, filename]
  2644. if use_bytes:
  2645. args = [os.fsencode(a) for a in args]
  2646. self.env = {os.fsencode(k): os.fsencode(v)
  2647. for k, v in self.env.items()}
  2648. return args
  2649. @requires_os_func('spawnl')
  2650. def test_spawnl(self):
  2651. args = self.create_args()
  2652. exitcode = os.spawnl(os.P_WAIT, args[0], *args)
  2653. self.assertEqual(exitcode, self.exitcode)
  2654. @requires_os_func('spawnle')
  2655. def test_spawnle(self):
  2656. args = self.create_args(with_env=True)
  2657. exitcode = os.spawnle(os.P_WAIT, args[0], *args, self.env)
  2658. self.assertEqual(exitcode, self.exitcode)
  2659. @requires_os_func('spawnlp')
  2660. def test_spawnlp(self):
  2661. args = self.create_args()
  2662. exitcode = os.spawnlp(os.P_WAIT, args[0], *args)
  2663. self.assertEqual(exitcode, self.exitcode)
  2664. @requires_os_func('spawnlpe')
  2665. def test_spawnlpe(self):
  2666. args = self.create_args(with_env=True)
  2667. exitcode = os.spawnlpe(os.P_WAIT, args[0], *args, self.env)
  2668. self.assertEqual(exitcode, self.exitcode)
  2669. @requires_os_func('spawnv')
  2670. def test_spawnv(self):
  2671. args = self.create_args()
  2672. exitcode = os.spawnv(os.P_WAIT, args[0], args)
  2673. self.assertEqual(exitcode, self.exitcode)
  2674. # Test for PyUnicode_FSConverter()
  2675. exitcode = os.spawnv(os.P_WAIT, FakePath(args[0]), args)
  2676. self.assertEqual(exitcode, self.exitcode)
  2677. @requires_os_func('spawnve')
  2678. def test_spawnve(self):
  2679. args = self.create_args(with_env=True)
  2680. exitcode = os.spawnve(os.P_WAIT, args[0], args, self.env)
  2681. self.assertEqual(exitcode, self.exitcode)
  2682. @requires_os_func('spawnvp')
  2683. def test_spawnvp(self):
  2684. args = self.create_args()
  2685. exitcode = os.spawnvp(os.P_WAIT, args[0], args)
  2686. self.assertEqual(exitcode, self.exitcode)
  2687. @requires_os_func('spawnvpe')
  2688. def test_spawnvpe(self):
  2689. args = self.create_args(with_env=True)
  2690. exitcode = os.spawnvpe(os.P_WAIT, args[0], args, self.env)
  2691. self.assertEqual(exitcode, self.exitcode)
  2692. @requires_os_func('spawnv')
  2693. def test_nowait(self):
  2694. args = self.create_args()
  2695. pid = os.spawnv(os.P_NOWAIT, args[0], args)
  2696. support.wait_process(pid, exitcode=self.exitcode)
  2697. @requires_os_func('spawnve')
  2698. def test_spawnve_bytes(self):
  2699. # Test bytes handling in parse_arglist and parse_envlist (#28114)
  2700. args = self.create_args(with_env=True, use_bytes=True)
  2701. exitcode = os.spawnve(os.P_WAIT, args[0], args, self.env)
  2702. self.assertEqual(exitcode, self.exitcode)
  2703. @requires_os_func('spawnl')
  2704. def test_spawnl_noargs(self):
  2705. args = self.create_args()
  2706. self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, args[0])
  2707. self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, args[0], '')
  2708. @requires_os_func('spawnle')
  2709. def test_spawnle_noargs(self):
  2710. args = self.create_args()
  2711. self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, args[0], {})
  2712. self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, args[0], '', {})
  2713. @requires_os_func('spawnv')
  2714. def test_spawnv_noargs(self):
  2715. args = self.create_args()
  2716. self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ())
  2717. self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], [])
  2718. self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], ('',))
  2719. self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, args[0], [''])
  2720. @requires_os_func('spawnve')
  2721. def test_spawnve_noargs(self):
  2722. args = self.create_args()
  2723. self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], (), {})
  2724. self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], [], {})
  2725. self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], ('',), {})
  2726. self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, args[0], [''], {})
  2727. def _test_invalid_env(self, spawn):
  2728. args = [sys.executable, '-c', 'pass']
  2729. # null character in the environment variable name
  2730. newenv = os.environ.copy()
  2731. newenv["FRUIT\0VEGETABLE"] = "cabbage"
  2732. try:
  2733. exitcode = spawn(os.P_WAIT, args[0], args, newenv)
  2734. except ValueError:
  2735. pass
  2736. else:
  2737. self.assertEqual(exitcode, 127)
  2738. # null character in the environment variable value
  2739. newenv = os.environ.copy()
  2740. newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
  2741. try:
  2742. exitcode = spawn(os.P_WAIT, args[0], args, newenv)
  2743. except ValueError:
  2744. pass
  2745. else:
  2746. self.assertEqual(exitcode, 127)
  2747. # equal character in the environment variable name
  2748. newenv = os.environ.copy()
  2749. newenv["FRUIT=ORANGE"] = "lemon"
  2750. try:
  2751. exitcode = spawn(os.P_WAIT, args[0], args, newenv)
  2752. except ValueError:
  2753. pass
  2754. else:
  2755. self.assertEqual(exitcode, 127)
  2756. # equal character in the environment variable value
  2757. filename = os_helper.TESTFN
  2758. self.addCleanup(os_helper.unlink, filename)
  2759. with open(filename, "w", encoding="utf-8") as fp:
  2760. fp.write('import sys, os\n'
  2761. 'if os.getenv("FRUIT") != "orange=lemon":\n'
  2762. ' raise AssertionError')
  2763. args = [sys.executable, filename]
  2764. newenv = os.environ.copy()
  2765. newenv["FRUIT"] = "orange=lemon"
  2766. exitcode = spawn(os.P_WAIT, args[0], args, newenv)
  2767. self.assertEqual(exitcode, 0)
  2768. @requires_os_func('spawnve')
  2769. def test_spawnve_invalid_env(self):
  2770. self._test_invalid_env(os.spawnve)
  2771. @requires_os_func('spawnvpe')
  2772. def test_spawnvpe_invalid_env(self):
  2773. self._test_invalid_env(os.spawnvpe)
  2774. # The introduction of this TestCase caused at least two different errors on
  2775. # *nix buildbots. Temporarily skip this to let the buildbots move along.
  2776. @unittest.skip("Skip due to platform/environment differences on *NIX buildbots")
  2777. @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin")
  2778. class LoginTests(unittest.TestCase):
  2779. def test_getlogin(self):
  2780. user_name = os.getlogin()
  2781. self.assertNotEqual(len(user_name), 0)
  2782. @unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
  2783. "needs os.getpriority and os.setpriority")
  2784. class ProgramPriorityTests(unittest.TestCase):
  2785. """Tests for os.getpriority() and os.setpriority()."""
  2786. def test_set_get_priority(self):
  2787. base = os.getpriority(os.PRIO_PROCESS, os.getpid())
  2788. os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
  2789. try:
  2790. new_prio = os.getpriority(os.PRIO_PROCESS, os.getpid())
  2791. if base >= 19 and new_prio <= 19:
  2792. raise unittest.SkipTest("unable to reliably test setpriority "
  2793. "at current nice level of %s" % base)
  2794. else:
  2795. self.assertEqual(new_prio, base + 1)
  2796. finally:
  2797. try:
  2798. os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
  2799. except OSError as err:
  2800. if err.errno != errno.EACCES:
  2801. raise
  2802. @unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
  2803. class TestSendfile(unittest.IsolatedAsyncioTestCase):
  2804. DATA = b"12345abcde" * 16 * 1024 # 160 KiB
  2805. SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
  2806. not sys.platform.startswith("solaris") and \
  2807. not sys.platform.startswith("sunos")
  2808. requires_headers_trailers = unittest.skipUnless(SUPPORT_HEADERS_TRAILERS,
  2809. 'requires headers and trailers support')
  2810. requires_32b = unittest.skipUnless(sys.maxsize < 2**32,
  2811. 'test is only meaningful on 32-bit builds')
  2812. @classmethod
  2813. def setUpClass(cls):
  2814. create_file(os_helper.TESTFN, cls.DATA)
  2815. @classmethod
  2816. def tearDownClass(cls):
  2817. os_helper.unlink(os_helper.TESTFN)
  2818. @staticmethod
  2819. async def chunks(reader):
  2820. while not reader.at_eof():
  2821. yield await reader.read()
  2822. async def handle_new_client(self, reader, writer):
  2823. self.server_buffer = b''.join([x async for x in self.chunks(reader)])
  2824. writer.close()
  2825. self.server.close() # The test server processes a single client only
  2826. async def asyncSetUp(self):
  2827. self.server_buffer = b''
  2828. self.server = await asyncio.start_server(self.handle_new_client,
  2829. socket_helper.HOSTv4)
  2830. server_name = self.server.sockets[0].getsockname()
  2831. self.client = socket.socket()
  2832. self.client.setblocking(False)
  2833. await asyncio.get_running_loop().sock_connect(self.client, server_name)
  2834. self.sockno = self.client.fileno()
  2835. self.file = open(os_helper.TESTFN, 'rb')
  2836. self.fileno = self.file.fileno()
  2837. async def asyncTearDown(self):
  2838. self.file.close()
  2839. self.client.close()
  2840. await self.server.wait_closed()
  2841. # Use the test subject instead of asyncio.loop.sendfile
  2842. @staticmethod
  2843. async def async_sendfile(*args, **kwargs):
  2844. return await asyncio.to_thread(os.sendfile, *args, **kwargs)
  2845. @staticmethod
  2846. async def sendfile_wrapper(*args, **kwargs):
  2847. """A higher level wrapper representing how an application is
  2848. supposed to use sendfile().
  2849. """
  2850. while True:
  2851. try:
  2852. return await TestSendfile.async_sendfile(*args, **kwargs)
  2853. except OSError as err:
  2854. if err.errno == errno.ECONNRESET:
  2855. # disconnected
  2856. raise
  2857. elif err.errno in (errno.EAGAIN, errno.EBUSY):
  2858. # we have to retry send data
  2859. continue
  2860. else:
  2861. raise
  2862. async def test_send_whole_file(self):
  2863. # normal send
  2864. total_sent = 0
  2865. offset = 0
  2866. nbytes = 4096
  2867. while total_sent < len(self.DATA):
  2868. sent = await self.sendfile_wrapper(self.sockno, self.fileno,
  2869. offset, nbytes)
  2870. if sent == 0:
  2871. break
  2872. offset += sent
  2873. total_sent += sent
  2874. self.assertTrue(sent <= nbytes)
  2875. self.assertEqual(offset, total_sent)
  2876. self.assertEqual(total_sent, len(self.DATA))
  2877. self.client.shutdown(socket.SHUT_RDWR)
  2878. self.client.close()
  2879. await self.server.wait_closed()
  2880. self.assertEqual(len(self.server_buffer), len(self.DATA))
  2881. self.assertEqual(self.server_buffer, self.DATA)
  2882. async def test_send_at_certain_offset(self):
  2883. # start sending a file at a certain offset
  2884. total_sent = 0
  2885. offset = len(self.DATA) // 2
  2886. must_send = len(self.DATA) - offset
  2887. nbytes = 4096
  2888. while total_sent < must_send:
  2889. sent = await self.sendfile_wrapper(self.sockno, self.fileno,
  2890. offset, nbytes)
  2891. if sent == 0:
  2892. break
  2893. offset += sent
  2894. total_sent += sent
  2895. self.assertTrue(sent <= nbytes)
  2896. self.client.shutdown(socket.SHUT_RDWR)
  2897. self.client.close()
  2898. await self.server.wait_closed()
  2899. expected = self.DATA[len(self.DATA) // 2:]
  2900. self.assertEqual(total_sent, len(expected))
  2901. self.assertEqual(len(self.server_buffer), len(expected))
  2902. self.assertEqual(self.server_buffer, expected)
  2903. async def test_offset_overflow(self):
  2904. # specify an offset > file size
  2905. offset = len(self.DATA) + 4096
  2906. try:
  2907. sent = await self.async_sendfile(self.sockno, self.fileno,
  2908. offset, 4096)
  2909. except OSError as e:
  2910. # Solaris can raise EINVAL if offset >= file length, ignore.
  2911. if e.errno != errno.EINVAL:
  2912. raise
  2913. else:
  2914. self.assertEqual(sent, 0)
  2915. self.client.shutdown(socket.SHUT_RDWR)
  2916. self.client.close()
  2917. await self.server.wait_closed()
  2918. self.assertEqual(self.server_buffer, b'')
  2919. async def test_invalid_offset(self):
  2920. with self.assertRaises(OSError) as cm:
  2921. await self.async_sendfile(self.sockno, self.fileno, -1, 4096)
  2922. self.assertEqual(cm.exception.errno, errno.EINVAL)
  2923. async def test_keywords(self):
  2924. # Keyword arguments should be supported
  2925. await self.async_sendfile(out_fd=self.sockno, in_fd=self.fileno,
  2926. offset=0, count=4096)
  2927. if self.SUPPORT_HEADERS_TRAILERS:
  2928. await self.async_sendfile(out_fd=self.sockno, in_fd=self.fileno,
  2929. offset=0, count=4096,
  2930. headers=(), trailers=(), flags=0)
  2931. # --- headers / trailers tests
  2932. @requires_headers_trailers
  2933. async def test_headers(self):
  2934. total_sent = 0
  2935. expected_data = b"x" * 512 + b"y" * 256 + self.DATA[:-1]
  2936. sent = await self.async_sendfile(self.sockno, self.fileno, 0, 4096,
  2937. headers=[b"x" * 512, b"y" * 256])
  2938. self.assertLessEqual(sent, 512 + 256 + 4096)
  2939. total_sent += sent
  2940. offset = 4096
  2941. while total_sent < len(expected_data):
  2942. nbytes = min(len(expected_data) - total_sent, 4096)
  2943. sent = await self.sendfile_wrapper(self.sockno, self.fileno,
  2944. offset, nbytes)
  2945. if sent == 0:
  2946. break
  2947. self.assertLessEqual(sent, nbytes)
  2948. total_sent += sent
  2949. offset += sent
  2950. self.assertEqual(total_sent, len(expected_data))
  2951. self.client.close()
  2952. await self.server.wait_closed()
  2953. self.assertEqual(hash(self.server_buffer), hash(expected_data))
  2954. @requires_headers_trailers
  2955. async def test_trailers(self):
  2956. TESTFN2 = os_helper.TESTFN + "2"
  2957. file_data = b"abcdef"
  2958. self.addCleanup(os_helper.unlink, TESTFN2)
  2959. create_file(TESTFN2, file_data)
  2960. with open(TESTFN2, 'rb') as f:
  2961. await self.async_sendfile(self.sockno, f.fileno(), 0, 5,
  2962. trailers=[b"123456", b"789"])
  2963. self.client.close()
  2964. await self.server.wait_closed()
  2965. self.assertEqual(self.server_buffer, b"abcde123456789")
  2966. @requires_headers_trailers
  2967. @requires_32b
  2968. async def test_headers_overflow_32bits(self):
  2969. self.server.handler_instance.accumulate = False
  2970. with self.assertRaises(OSError) as cm:
  2971. await self.async_sendfile(self.sockno, self.fileno, 0, 0,
  2972. headers=[b"x" * 2**16] * 2**15)
  2973. self.assertEqual(cm.exception.errno, errno.EINVAL)
  2974. @requires_headers_trailers
  2975. @requires_32b
  2976. async def test_trailers_overflow_32bits(self):
  2977. self.server.handler_instance.accumulate = False
  2978. with self.assertRaises(OSError) as cm:
  2979. await self.async_sendfile(self.sockno, self.fileno, 0, 0,
  2980. trailers=[b"x" * 2**16] * 2**15)
  2981. self.assertEqual(cm.exception.errno, errno.EINVAL)
  2982. @requires_headers_trailers
  2983. @unittest.skipUnless(hasattr(os, 'SF_NODISKIO'),
  2984. 'test needs os.SF_NODISKIO')
  2985. async def test_flags(self):
  2986. try:
  2987. await self.async_sendfile(self.sockno, self.fileno, 0, 4096,
  2988. flags=os.SF_NODISKIO)
  2989. except OSError as err:
  2990. if err.errno not in (errno.EBUSY, errno.EAGAIN):
  2991. raise
  2992. def supports_extended_attributes():
  2993. if not hasattr(os, "setxattr"):
  2994. return False
  2995. try:
  2996. with open(os_helper.TESTFN, "xb", 0) as fp:
  2997. try:
  2998. os.setxattr(fp.fileno(), b"user.test", b"")
  2999. except OSError:
  3000. return False
  3001. finally:
  3002. os_helper.unlink(os_helper.TESTFN)
  3003. return True
  3004. @unittest.skipUnless(supports_extended_attributes(),
  3005. "no non-broken extended attribute support")
  3006. # Kernels < 2.6.39 don't respect setxattr flags.
  3007. @support.requires_linux_version(2, 6, 39)
  3008. class ExtendedAttributeTests(unittest.TestCase):
  3009. def _check_xattrs_str(self, s, getxattr, setxattr, removexattr, listxattr, **kwargs):
  3010. fn = os_helper.TESTFN
  3011. self.addCleanup(os_helper.unlink, fn)
  3012. create_file(fn)
  3013. with self.assertRaises(OSError) as cm:
  3014. getxattr(fn, s("user.test"), **kwargs)
  3015. self.assertEqual(cm.exception.errno, errno.ENODATA)
  3016. init_xattr = listxattr(fn)
  3017. self.assertIsInstance(init_xattr, list)
  3018. setxattr(fn, s("user.test"), b"", **kwargs)
  3019. xattr = set(init_xattr)
  3020. xattr.add("user.test")
  3021. self.assertEqual(set(listxattr(fn)), xattr)
  3022. self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"")
  3023. setxattr(fn, s("user.test"), b"hello", os.XATTR_REPLACE, **kwargs)
  3024. self.assertEqual(getxattr(fn, b"user.test", **kwargs), b"hello")
  3025. with self.assertRaises(OSError) as cm:
  3026. setxattr(fn, s("user.test"), b"bye", os.XATTR_CREATE, **kwargs)
  3027. self.assertEqual(cm.exception.errno, errno.EEXIST)
  3028. with self.assertRaises(OSError) as cm:
  3029. setxattr(fn, s("user.test2"), b"bye", os.XATTR_REPLACE, **kwargs)
  3030. self.assertEqual(cm.exception.errno, errno.ENODATA)
  3031. setxattr(fn, s("user.test2"), b"foo", os.XATTR_CREATE, **kwargs)
  3032. xattr.add("user.test2")
  3033. self.assertEqual(set(listxattr(fn)), xattr)
  3034. removexattr(fn, s("user.test"), **kwargs)
  3035. with self.assertRaises(OSError) as cm:
  3036. getxattr(fn, s("user.test"), **kwargs)
  3037. self.assertEqual(cm.exception.errno, errno.ENODATA)
  3038. xattr.remove("user.test")
  3039. self.assertEqual(set(listxattr(fn)), xattr)
  3040. self.assertEqual(getxattr(fn, s("user.test2"), **kwargs), b"foo")
  3041. setxattr(fn, s("user.test"), b"a"*1024, **kwargs)
  3042. self.assertEqual(getxattr(fn, s("user.test"), **kwargs), b"a"*1024)
  3043. removexattr(fn, s("user.test"), **kwargs)
  3044. many = sorted("user.test{}".format(i) for i in range(100))
  3045. for thing in many:
  3046. setxattr(fn, thing, b"x", **kwargs)
  3047. self.assertEqual(set(listxattr(fn)), set(init_xattr) | set(many))
  3048. def _check_xattrs(self, *args, **kwargs):
  3049. self._check_xattrs_str(str, *args, **kwargs)
  3050. os_helper.unlink(os_helper.TESTFN)
  3051. self._check_xattrs_str(os.fsencode, *args, **kwargs)
  3052. os_helper.unlink(os_helper.TESTFN)
  3053. def test_simple(self):
  3054. self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
  3055. os.listxattr)
  3056. def test_lpath(self):
  3057. self._check_xattrs(os.getxattr, os.setxattr, os.removexattr,
  3058. os.listxattr, follow_symlinks=False)
  3059. def test_fds(self):
  3060. def getxattr(path, *args):
  3061. with open(path, "rb") as fp:
  3062. return os.getxattr(fp.fileno(), *args)
  3063. def setxattr(path, *args):
  3064. with open(path, "wb", 0) as fp:
  3065. os.setxattr(fp.fileno(), *args)
  3066. def removexattr(path, *args):
  3067. with open(path, "wb", 0) as fp:
  3068. os.removexattr(fp.fileno(), *args)
  3069. def listxattr(path, *args):
  3070. with open(path, "rb") as fp:
  3071. return os.listxattr(fp.fileno(), *args)
  3072. self._check_xattrs(getxattr, setxattr, removexattr, listxattr)
  3073. @unittest.skipUnless(hasattr(os, 'get_terminal_size'), "requires os.get_terminal_size")
  3074. class TermsizeTests(unittest.TestCase):
  3075. def test_does_not_crash(self):
  3076. """Check if get_terminal_size() returns a meaningful value.
  3077. There's no easy portable way to actually check the size of the
  3078. terminal, so let's check if it returns something sensible instead.
  3079. """
  3080. try:
  3081. size = os.get_terminal_size()
  3082. except OSError as e:
  3083. if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
  3084. # Under win32 a generic OSError can be thrown if the
  3085. # handle cannot be retrieved
  3086. self.skipTest("failed to query terminal size")
  3087. raise
  3088. self.assertGreaterEqual(size.columns, 0)
  3089. self.assertGreaterEqual(size.lines, 0)
  3090. def test_stty_match(self):
  3091. """Check if stty returns the same results
  3092. stty actually tests stdin, so get_terminal_size is invoked on
  3093. stdin explicitly. If stty succeeded, then get_terminal_size()
  3094. should work too.
  3095. """
  3096. try:
  3097. size = (
  3098. subprocess.check_output(
  3099. ["stty", "size"], stderr=subprocess.DEVNULL, text=True
  3100. ).split()
  3101. )
  3102. except (FileNotFoundError, subprocess.CalledProcessError,
  3103. PermissionError):
  3104. self.skipTest("stty invocation failed")
  3105. expected = (int(size[1]), int(size[0])) # reversed order
  3106. try:
  3107. actual = os.get_terminal_size(sys.__stdin__.fileno())
  3108. except OSError as e:
  3109. if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY):
  3110. # Under win32 a generic OSError can be thrown if the
  3111. # handle cannot be retrieved
  3112. self.skipTest("failed to query terminal size")
  3113. raise
  3114. self.assertEqual(expected, actual)
  3115. @unittest.skipUnless(hasattr(os, 'memfd_create'), 'requires os.memfd_create')
  3116. @support.requires_linux_version(3, 17)
  3117. class MemfdCreateTests(unittest.TestCase):
  3118. def test_memfd_create(self):
  3119. fd = os.memfd_create("Hi", os.MFD_CLOEXEC)
  3120. self.assertNotEqual(fd, -1)
  3121. self.addCleanup(os.close, fd)
  3122. self.assertFalse(os.get_inheritable(fd))
  3123. with open(fd, "wb", closefd=False) as f:
  3124. f.write(b'memfd_create')
  3125. self.assertEqual(f.tell(), 12)
  3126. fd2 = os.memfd_create("Hi")
  3127. self.addCleanup(os.close, fd2)
  3128. self.assertFalse(os.get_inheritable(fd2))
  3129. @unittest.skipUnless(hasattr(os, 'eventfd'), 'requires os.eventfd')
  3130. @support.requires_linux_version(2, 6, 30)
  3131. class EventfdTests(unittest.TestCase):
  3132. def test_eventfd_initval(self):
  3133. def pack(value):
  3134. """Pack as native uint64_t
  3135. """
  3136. return struct.pack("@Q", value)
  3137. size = 8 # read/write 8 bytes
  3138. initval = 42
  3139. fd = os.eventfd(initval)
  3140. self.assertNotEqual(fd, -1)
  3141. self.addCleanup(os.close, fd)
  3142. self.assertFalse(os.get_inheritable(fd))
  3143. # test with raw read/write
  3144. res = os.read(fd, size)
  3145. self.assertEqual(res, pack(initval))
  3146. os.write(fd, pack(23))
  3147. res = os.read(fd, size)
  3148. self.assertEqual(res, pack(23))
  3149. os.write(fd, pack(40))
  3150. os.write(fd, pack(2))
  3151. res = os.read(fd, size)
  3152. self.assertEqual(res, pack(42))
  3153. # test with eventfd_read/eventfd_write
  3154. os.eventfd_write(fd, 20)
  3155. os.eventfd_write(fd, 3)
  3156. res = os.eventfd_read(fd)
  3157. self.assertEqual(res, 23)
  3158. def test_eventfd_semaphore(self):
  3159. initval = 2
  3160. flags = os.EFD_CLOEXEC | os.EFD_SEMAPHORE | os.EFD_NONBLOCK
  3161. fd = os.eventfd(initval, flags)
  3162. self.assertNotEqual(fd, -1)
  3163. self.addCleanup(os.close, fd)
  3164. # semaphore starts has initval 2, two reads return '1'
  3165. res = os.eventfd_read(fd)
  3166. self.assertEqual(res, 1)
  3167. res = os.eventfd_read(fd)
  3168. self.assertEqual(res, 1)
  3169. # third read would block
  3170. with self.assertRaises(BlockingIOError):
  3171. os.eventfd_read(fd)
  3172. with self.assertRaises(BlockingIOError):
  3173. os.read(fd, 8)
  3174. # increase semaphore counter, read one
  3175. os.eventfd_write(fd, 1)
  3176. res = os.eventfd_read(fd)
  3177. self.assertEqual(res, 1)
  3178. # next read would block, too
  3179. with self.assertRaises(BlockingIOError):
  3180. os.eventfd_read(fd)
  3181. def test_eventfd_select(self):
  3182. flags = os.EFD_CLOEXEC | os.EFD_NONBLOCK
  3183. fd = os.eventfd(0, flags)
  3184. self.assertNotEqual(fd, -1)
  3185. self.addCleanup(os.close, fd)
  3186. # counter is zero, only writeable
  3187. rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
  3188. self.assertEqual((rfd, wfd, xfd), ([], [fd], []))
  3189. # counter is non-zero, read and writeable
  3190. os.eventfd_write(fd, 23)
  3191. rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
  3192. self.assertEqual((rfd, wfd, xfd), ([fd], [fd], []))
  3193. self.assertEqual(os.eventfd_read(fd), 23)
  3194. # counter at max, only readable
  3195. os.eventfd_write(fd, (2**64) - 2)
  3196. rfd, wfd, xfd = select.select([fd], [fd], [fd], 0)
  3197. self.assertEqual((rfd, wfd, xfd), ([fd], [], []))
  3198. os.eventfd_read(fd)
  3199. class OSErrorTests(unittest.TestCase):
  3200. def setUp(self):
  3201. class Str(str):
  3202. pass
  3203. self.bytes_filenames = []
  3204. self.unicode_filenames = []
  3205. if os_helper.TESTFN_UNENCODABLE is not None:
  3206. decoded = os_helper.TESTFN_UNENCODABLE
  3207. else:
  3208. decoded = os_helper.TESTFN
  3209. self.unicode_filenames.append(decoded)
  3210. self.unicode_filenames.append(Str(decoded))
  3211. if os_helper.TESTFN_UNDECODABLE is not None:
  3212. encoded = os_helper.TESTFN_UNDECODABLE
  3213. else:
  3214. encoded = os.fsencode(os_helper.TESTFN)
  3215. self.bytes_filenames.append(encoded)
  3216. self.bytes_filenames.append(bytearray(encoded))
  3217. self.bytes_filenames.append(memoryview(encoded))
  3218. self.filenames = self.bytes_filenames + self.unicode_filenames
  3219. def test_oserror_filename(self):
  3220. funcs = [
  3221. (self.filenames, os.chdir,),
  3222. (self.filenames, os.lstat,),
  3223. (self.filenames, os.open, os.O_RDONLY),
  3224. (self.filenames, os.rmdir,),
  3225. (self.filenames, os.stat,),
  3226. (self.filenames, os.unlink,),
  3227. ]
  3228. if sys.platform == "win32":
  3229. funcs.extend((
  3230. (self.bytes_filenames, os.rename, b"dst"),
  3231. (self.bytes_filenames, os.replace, b"dst"),
  3232. (self.unicode_filenames, os.rename, "dst"),
  3233. (self.unicode_filenames, os.replace, "dst"),
  3234. (self.unicode_filenames, os.listdir, ),
  3235. ))
  3236. else:
  3237. funcs.extend((
  3238. (self.filenames, os.listdir,),
  3239. (self.filenames, os.rename, "dst"),
  3240. (self.filenames, os.replace, "dst"),
  3241. ))
  3242. if os_helper.can_chmod():
  3243. funcs.append((self.filenames, os.chmod, 0o777))
  3244. if hasattr(os, "chown"):
  3245. funcs.append((self.filenames, os.chown, 0, 0))
  3246. if hasattr(os, "lchown"):
  3247. funcs.append((self.filenames, os.lchown, 0, 0))
  3248. if hasattr(os, "truncate"):
  3249. funcs.append((self.filenames, os.truncate, 0))
  3250. if hasattr(os, "chflags"):
  3251. funcs.append((self.filenames, os.chflags, 0))
  3252. if hasattr(os, "lchflags"):
  3253. funcs.append((self.filenames, os.lchflags, 0))
  3254. if hasattr(os, "chroot"):
  3255. funcs.append((self.filenames, os.chroot,))
  3256. if hasattr(os, "link"):
  3257. if sys.platform == "win32":
  3258. funcs.append((self.bytes_filenames, os.link, b"dst"))
  3259. funcs.append((self.unicode_filenames, os.link, "dst"))
  3260. else:
  3261. funcs.append((self.filenames, os.link, "dst"))
  3262. if hasattr(os, "listxattr"):
  3263. funcs.extend((
  3264. (self.filenames, os.listxattr,),
  3265. (self.filenames, os.getxattr, "user.test"),
  3266. (self.filenames, os.setxattr, "user.test", b'user'),
  3267. (self.filenames, os.removexattr, "user.test"),
  3268. ))
  3269. if hasattr(os, "lchmod"):
  3270. funcs.append((self.filenames, os.lchmod, 0o777))
  3271. if hasattr(os, "readlink"):
  3272. funcs.append((self.filenames, os.readlink,))
  3273. for filenames, func, *func_args in funcs:
  3274. for name in filenames:
  3275. try:
  3276. if isinstance(name, (str, bytes)):
  3277. func(name, *func_args)
  3278. else:
  3279. with self.assertWarnsRegex(DeprecationWarning, 'should be'):
  3280. func(name, *func_args)
  3281. except OSError as err:
  3282. self.assertIs(err.filename, name, str(func))
  3283. except UnicodeDecodeError:
  3284. pass
  3285. else:
  3286. self.fail("No exception thrown by {}".format(func))
  3287. class CPUCountTests(unittest.TestCase):
  3288. def test_cpu_count(self):
  3289. cpus = os.cpu_count()
  3290. if cpus is not None:
  3291. self.assertIsInstance(cpus, int)
  3292. self.assertGreater(cpus, 0)
  3293. else:
  3294. self.skipTest("Could not determine the number of CPUs")
  3295. # FD inheritance check is only useful for systems with process support.
  3296. @support.requires_subprocess()
  3297. class FDInheritanceTests(unittest.TestCase):
  3298. def test_get_set_inheritable(self):
  3299. fd = os.open(__file__, os.O_RDONLY)
  3300. self.addCleanup(os.close, fd)
  3301. self.assertEqual(os.get_inheritable(fd), False)
  3302. os.set_inheritable(fd, True)
  3303. self.assertEqual(os.get_inheritable(fd), True)
  3304. @unittest.skipIf(fcntl is None, "need fcntl")
  3305. def test_get_inheritable_cloexec(self):
  3306. fd = os.open(__file__, os.O_RDONLY)
  3307. self.addCleanup(os.close, fd)
  3308. self.assertEqual(os.get_inheritable(fd), False)
  3309. # clear FD_CLOEXEC flag
  3310. flags = fcntl.fcntl(fd, fcntl.F_GETFD)
  3311. flags &= ~fcntl.FD_CLOEXEC
  3312. fcntl.fcntl(fd, fcntl.F_SETFD, flags)
  3313. self.assertEqual(os.get_inheritable(fd), True)
  3314. @unittest.skipIf(fcntl is None, "need fcntl")
  3315. def test_set_inheritable_cloexec(self):
  3316. fd = os.open(__file__, os.O_RDONLY)
  3317. self.addCleanup(os.close, fd)
  3318. self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
  3319. fcntl.FD_CLOEXEC)
  3320. os.set_inheritable(fd, True)
  3321. self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
  3322. 0)
  3323. @unittest.skipUnless(hasattr(os, 'O_PATH'), "need os.O_PATH")
  3324. def test_get_set_inheritable_o_path(self):
  3325. fd = os.open(__file__, os.O_PATH)
  3326. self.addCleanup(os.close, fd)
  3327. self.assertEqual(os.get_inheritable(fd), False)
  3328. os.set_inheritable(fd, True)
  3329. self.assertEqual(os.get_inheritable(fd), True)
  3330. os.set_inheritable(fd, False)
  3331. self.assertEqual(os.get_inheritable(fd), False)
  3332. def test_get_set_inheritable_badf(self):
  3333. fd = os_helper.make_bad_fd()
  3334. with self.assertRaises(OSError) as ctx:
  3335. os.get_inheritable(fd)
  3336. self.assertEqual(ctx.exception.errno, errno.EBADF)
  3337. with self.assertRaises(OSError) as ctx:
  3338. os.set_inheritable(fd, True)
  3339. self.assertEqual(ctx.exception.errno, errno.EBADF)
  3340. with self.assertRaises(OSError) as ctx:
  3341. os.set_inheritable(fd, False)
  3342. self.assertEqual(ctx.exception.errno, errno.EBADF)
  3343. def test_open(self):
  3344. fd = os.open(__file__, os.O_RDONLY)
  3345. self.addCleanup(os.close, fd)
  3346. self.assertEqual(os.get_inheritable(fd), False)
  3347. @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()")
  3348. def test_pipe(self):
  3349. rfd, wfd = os.pipe()
  3350. self.addCleanup(os.close, rfd)
  3351. self.addCleanup(os.close, wfd)
  3352. self.assertEqual(os.get_inheritable(rfd), False)
  3353. self.assertEqual(os.get_inheritable(wfd), False)
  3354. def test_dup(self):
  3355. fd1 = os.open(__file__, os.O_RDONLY)
  3356. self.addCleanup(os.close, fd1)
  3357. fd2 = os.dup(fd1)
  3358. self.addCleanup(os.close, fd2)
  3359. self.assertEqual(os.get_inheritable(fd2), False)
  3360. def test_dup_standard_stream(self):
  3361. fd = os.dup(1)
  3362. self.addCleanup(os.close, fd)
  3363. self.assertGreater(fd, 0)
  3364. @unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
  3365. def test_dup_nul(self):
  3366. # os.dup() was creating inheritable fds for character files.
  3367. fd1 = os.open('NUL', os.O_RDONLY)
  3368. self.addCleanup(os.close, fd1)
  3369. fd2 = os.dup(fd1)
  3370. self.addCleanup(os.close, fd2)
  3371. self.assertFalse(os.get_inheritable(fd2))
  3372. @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
  3373. def test_dup2(self):
  3374. fd = os.open(__file__, os.O_RDONLY)
  3375. self.addCleanup(os.close, fd)
  3376. # inheritable by default
  3377. fd2 = os.open(__file__, os.O_RDONLY)
  3378. self.addCleanup(os.close, fd2)
  3379. self.assertEqual(os.dup2(fd, fd2), fd2)
  3380. self.assertTrue(os.get_inheritable(fd2))
  3381. # force non-inheritable
  3382. fd3 = os.open(__file__, os.O_RDONLY)
  3383. self.addCleanup(os.close, fd3)
  3384. self.assertEqual(os.dup2(fd, fd3, inheritable=False), fd3)
  3385. self.assertFalse(os.get_inheritable(fd3))
  3386. @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()")
  3387. def test_openpty(self):
  3388. master_fd, slave_fd = os.openpty()
  3389. self.addCleanup(os.close, master_fd)
  3390. self.addCleanup(os.close, slave_fd)
  3391. self.assertEqual(os.get_inheritable(master_fd), False)
  3392. self.assertEqual(os.get_inheritable(slave_fd), False)
  3393. class PathTConverterTests(unittest.TestCase):
  3394. # tuples of (function name, allows fd arguments, additional arguments to
  3395. # function, cleanup function)
  3396. functions = [
  3397. ('stat', True, (), None),
  3398. ('lstat', False, (), None),
  3399. ('access', False, (os.F_OK,), None),
  3400. ('chflags', False, (0,), None),
  3401. ('lchflags', False, (0,), None),
  3402. ('open', False, (os.O_RDONLY,), getattr(os, 'close', None)),
  3403. ]
  3404. def test_path_t_converter(self):
  3405. str_filename = os_helper.TESTFN
  3406. if os.name == 'nt':
  3407. bytes_fspath = bytes_filename = None
  3408. else:
  3409. bytes_filename = os.fsencode(os_helper.TESTFN)
  3410. bytes_fspath = FakePath(bytes_filename)
  3411. fd = os.open(FakePath(str_filename), os.O_WRONLY|os.O_CREAT)
  3412. self.addCleanup(os_helper.unlink, os_helper.TESTFN)
  3413. self.addCleanup(os.close, fd)
  3414. int_fspath = FakePath(fd)
  3415. str_fspath = FakePath(str_filename)
  3416. for name, allow_fd, extra_args, cleanup_fn in self.functions:
  3417. with self.subTest(name=name):
  3418. try:
  3419. fn = getattr(os, name)
  3420. except AttributeError:
  3421. continue
  3422. for path in (str_filename, bytes_filename, str_fspath,
  3423. bytes_fspath):
  3424. if path is None:
  3425. continue
  3426. with self.subTest(name=name, path=path):
  3427. result = fn(path, *extra_args)
  3428. if cleanup_fn is not None:
  3429. cleanup_fn(result)
  3430. with self.assertRaisesRegex(
  3431. TypeError, 'to return str or bytes'):
  3432. fn(int_fspath, *extra_args)
  3433. if allow_fd:
  3434. result = fn(fd, *extra_args) # should not fail
  3435. if cleanup_fn is not None:
  3436. cleanup_fn(result)
  3437. else:
  3438. with self.assertRaisesRegex(
  3439. TypeError,
  3440. 'os.PathLike'):
  3441. fn(fd, *extra_args)
  3442. def test_path_t_converter_and_custom_class(self):
  3443. msg = r'__fspath__\(\) to return str or bytes, not %s'
  3444. with self.assertRaisesRegex(TypeError, msg % r'int'):
  3445. os.stat(FakePath(2))
  3446. with self.assertRaisesRegex(TypeError, msg % r'float'):
  3447. os.stat(FakePath(2.34))
  3448. with self.assertRaisesRegex(TypeError, msg % r'object'):
  3449. os.stat(FakePath(object()))
  3450. @unittest.skipUnless(hasattr(os, 'get_blocking'),
  3451. 'needs os.get_blocking() and os.set_blocking()')
  3452. @unittest.skipIf(support.is_emscripten, "Cannot unset blocking flag")
  3453. class BlockingTests(unittest.TestCase):
  3454. def test_blocking(self):
  3455. fd = os.open(__file__, os.O_RDONLY)
  3456. self.addCleanup(os.close, fd)
  3457. self.assertEqual(os.get_blocking(fd), True)
  3458. os.set_blocking(fd, False)
  3459. self.assertEqual(os.get_blocking(fd), False)
  3460. os.set_blocking(fd, True)
  3461. self.assertEqual(os.get_blocking(fd), True)
  3462. class ExportsTests(unittest.TestCase):
  3463. def test_os_all(self):
  3464. self.assertIn('open', os.__all__)
  3465. self.assertIn('walk', os.__all__)
  3466. class TestDirEntry(unittest.TestCase):
  3467. def setUp(self):
  3468. self.path = os.path.realpath(os_helper.TESTFN)
  3469. self.addCleanup(os_helper.rmtree, self.path)
  3470. os.mkdir(self.path)
  3471. def test_uninstantiable(self):
  3472. self.assertRaises(TypeError, os.DirEntry)
  3473. def test_unpickable(self):
  3474. filename = create_file(os.path.join(self.path, "file.txt"), b'python')
  3475. entry = [entry for entry in os.scandir(self.path)].pop()
  3476. self.assertIsInstance(entry, os.DirEntry)
  3477. self.assertEqual(entry.name, "file.txt")
  3478. import pickle
  3479. self.assertRaises(TypeError, pickle.dumps, entry, filename)
  3480. class TestScandir(unittest.TestCase):
  3481. check_no_resource_warning = warnings_helper.check_no_resource_warning
  3482. def setUp(self):
  3483. self.path = os.path.realpath(os_helper.TESTFN)
  3484. self.bytes_path = os.fsencode(self.path)
  3485. self.addCleanup(os_helper.rmtree, self.path)
  3486. os.mkdir(self.path)
  3487. def create_file(self, name="file.txt"):
  3488. path = self.bytes_path if isinstance(name, bytes) else self.path
  3489. filename = os.path.join(path, name)
  3490. create_file(filename, b'python')
  3491. return filename
  3492. def get_entries(self, names):
  3493. entries = dict((entry.name, entry)
  3494. for entry in os.scandir(self.path))
  3495. self.assertEqual(sorted(entries.keys()), names)
  3496. return entries
  3497. def assert_stat_equal(self, stat1, stat2, skip_fields):
  3498. if skip_fields:
  3499. for attr in dir(stat1):
  3500. if not attr.startswith("st_"):
  3501. continue
  3502. if attr in ("st_dev", "st_ino", "st_nlink"):
  3503. continue
  3504. self.assertEqual(getattr(stat1, attr),
  3505. getattr(stat2, attr),
  3506. (stat1, stat2, attr))
  3507. else:
  3508. self.assertEqual(stat1, stat2)
  3509. def test_uninstantiable(self):
  3510. scandir_iter = os.scandir(self.path)
  3511. self.assertRaises(TypeError, type(scandir_iter))
  3512. scandir_iter.close()
  3513. def test_unpickable(self):
  3514. filename = self.create_file("file.txt")
  3515. scandir_iter = os.scandir(self.path)
  3516. import pickle
  3517. self.assertRaises(TypeError, pickle.dumps, scandir_iter, filename)
  3518. scandir_iter.close()
  3519. def check_entry(self, entry, name, is_dir, is_file, is_symlink):
  3520. self.assertIsInstance(entry, os.DirEntry)
  3521. self.assertEqual(entry.name, name)
  3522. self.assertEqual(entry.path, os.path.join(self.path, name))
  3523. self.assertEqual(entry.inode(),
  3524. os.stat(entry.path, follow_symlinks=False).st_ino)
  3525. entry_stat = os.stat(entry.path)
  3526. self.assertEqual(entry.is_dir(),
  3527. stat.S_ISDIR(entry_stat.st_mode))
  3528. self.assertEqual(entry.is_file(),
  3529. stat.S_ISREG(entry_stat.st_mode))
  3530. self.assertEqual(entry.is_symlink(),
  3531. os.path.islink(entry.path))
  3532. entry_lstat = os.stat(entry.path, follow_symlinks=False)
  3533. self.assertEqual(entry.is_dir(follow_symlinks=False),
  3534. stat.S_ISDIR(entry_lstat.st_mode))
  3535. self.assertEqual(entry.is_file(follow_symlinks=False),
  3536. stat.S_ISREG(entry_lstat.st_mode))
  3537. self.assert_stat_equal(entry.stat(),
  3538. entry_stat,
  3539. os.name == 'nt' and not is_symlink)
  3540. self.assert_stat_equal(entry.stat(follow_symlinks=False),
  3541. entry_lstat,
  3542. os.name == 'nt')
  3543. def test_attributes(self):
  3544. link = hasattr(os, 'link')
  3545. symlink = os_helper.can_symlink()
  3546. dirname = os.path.join(self.path, "dir")
  3547. os.mkdir(dirname)
  3548. filename = self.create_file("file.txt")
  3549. if link:
  3550. try:
  3551. os.link(filename, os.path.join(self.path, "link_file.txt"))
  3552. except PermissionError as e:
  3553. self.skipTest('os.link(): %s' % e)
  3554. if symlink:
  3555. os.symlink(dirname, os.path.join(self.path, "symlink_dir"),
  3556. target_is_directory=True)
  3557. os.symlink(filename, os.path.join(self.path, "symlink_file.txt"))
  3558. names = ['dir', 'file.txt']
  3559. if link:
  3560. names.append('link_file.txt')
  3561. if symlink:
  3562. names.extend(('symlink_dir', 'symlink_file.txt'))
  3563. entries = self.get_entries(names)
  3564. entry = entries['dir']
  3565. self.check_entry(entry, 'dir', True, False, False)
  3566. entry = entries['file.txt']
  3567. self.check_entry(entry, 'file.txt', False, True, False)
  3568. if link:
  3569. entry = entries['link_file.txt']
  3570. self.check_entry(entry, 'link_file.txt', False, True, False)
  3571. if symlink:
  3572. entry = entries['symlink_dir']
  3573. self.check_entry(entry, 'symlink_dir', True, False, True)
  3574. entry = entries['symlink_file.txt']
  3575. self.check_entry(entry, 'symlink_file.txt', False, True, True)
  3576. def get_entry(self, name):
  3577. path = self.bytes_path if isinstance(name, bytes) else self.path
  3578. entries = list(os.scandir(path))
  3579. self.assertEqual(len(entries), 1)
  3580. entry = entries[0]
  3581. self.assertEqual(entry.name, name)
  3582. return entry
  3583. def create_file_entry(self, name='file.txt'):
  3584. filename = self.create_file(name=name)
  3585. return self.get_entry(os.path.basename(filename))
  3586. def test_current_directory(self):
  3587. filename = self.create_file()
  3588. old_dir = os.getcwd()
  3589. try:
  3590. os.chdir(self.path)
  3591. # call scandir() without parameter: it must list the content
  3592. # of the current directory
  3593. entries = dict((entry.name, entry) for entry in os.scandir())
  3594. self.assertEqual(sorted(entries.keys()),
  3595. [os.path.basename(filename)])
  3596. finally:
  3597. os.chdir(old_dir)
  3598. def test_repr(self):
  3599. entry = self.create_file_entry()
  3600. self.assertEqual(repr(entry), "<DirEntry 'file.txt'>")
  3601. def test_fspath_protocol(self):
  3602. entry = self.create_file_entry()
  3603. self.assertEqual(os.fspath(entry), os.path.join(self.path, 'file.txt'))
  3604. def test_fspath_protocol_bytes(self):
  3605. bytes_filename = os.fsencode('bytesfile.txt')
  3606. bytes_entry = self.create_file_entry(name=bytes_filename)
  3607. fspath = os.fspath(bytes_entry)
  3608. self.assertIsInstance(fspath, bytes)
  3609. self.assertEqual(fspath,
  3610. os.path.join(os.fsencode(self.path),bytes_filename))
  3611. def test_removed_dir(self):
  3612. path = os.path.join(self.path, 'dir')
  3613. os.mkdir(path)
  3614. entry = self.get_entry('dir')
  3615. os.rmdir(path)
  3616. # On POSIX, is_dir() result depends if scandir() filled d_type or not
  3617. if os.name == 'nt':
  3618. self.assertTrue(entry.is_dir())
  3619. self.assertFalse(entry.is_file())
  3620. self.assertFalse(entry.is_symlink())
  3621. if os.name == 'nt':
  3622. self.assertRaises(FileNotFoundError, entry.inode)
  3623. # don't fail
  3624. entry.stat()
  3625. entry.stat(follow_symlinks=False)
  3626. else:
  3627. self.assertGreater(entry.inode(), 0)
  3628. self.assertRaises(FileNotFoundError, entry.stat)
  3629. self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False)
  3630. def test_removed_file(self):
  3631. entry = self.create_file_entry()
  3632. os.unlink(entry.path)
  3633. self.assertFalse(entry.is_dir())
  3634. # On POSIX, is_dir() result depends if scandir() filled d_type or not
  3635. if os.name == 'nt':
  3636. self.assertTrue(entry.is_file())
  3637. self.assertFalse(entry.is_symlink())
  3638. if os.name == 'nt':
  3639. self.assertRaises(FileNotFoundError, entry.inode)
  3640. # don't fail
  3641. entry.stat()
  3642. entry.stat(follow_symlinks=False)
  3643. else:
  3644. self.assertGreater(entry.inode(), 0)
  3645. self.assertRaises(FileNotFoundError, entry.stat)
  3646. self.assertRaises(FileNotFoundError, entry.stat, follow_symlinks=False)
  3647. def test_broken_symlink(self):
  3648. if not os_helper.can_symlink():
  3649. return self.skipTest('cannot create symbolic link')
  3650. filename = self.create_file("file.txt")
  3651. os.symlink(filename,
  3652. os.path.join(self.path, "symlink.txt"))
  3653. entries = self.get_entries(['file.txt', 'symlink.txt'])
  3654. entry = entries['symlink.txt']
  3655. os.unlink(filename)
  3656. self.assertGreater(entry.inode(), 0)
  3657. self.assertFalse(entry.is_dir())
  3658. self.assertFalse(entry.is_file()) # broken symlink returns False
  3659. self.assertFalse(entry.is_dir(follow_symlinks=False))
  3660. self.assertFalse(entry.is_file(follow_symlinks=False))
  3661. self.assertTrue(entry.is_symlink())
  3662. self.assertRaises(FileNotFoundError, entry.stat)
  3663. # don't fail
  3664. entry.stat(follow_symlinks=False)
  3665. def test_bytes(self):
  3666. self.create_file("file.txt")
  3667. path_bytes = os.fsencode(self.path)
  3668. entries = list(os.scandir(path_bytes))
  3669. self.assertEqual(len(entries), 1, entries)
  3670. entry = entries[0]
  3671. self.assertEqual(entry.name, b'file.txt')
  3672. self.assertEqual(entry.path,
  3673. os.fsencode(os.path.join(self.path, 'file.txt')))
  3674. def test_bytes_like(self):
  3675. self.create_file("file.txt")
  3676. for cls in bytearray, memoryview:
  3677. path_bytes = cls(os.fsencode(self.path))
  3678. with self.assertWarns(DeprecationWarning):
  3679. entries = list(os.scandir(path_bytes))
  3680. self.assertEqual(len(entries), 1, entries)
  3681. entry = entries[0]
  3682. self.assertEqual(entry.name, b'file.txt')
  3683. self.assertEqual(entry.path,
  3684. os.fsencode(os.path.join(self.path, 'file.txt')))
  3685. self.assertIs(type(entry.name), bytes)
  3686. self.assertIs(type(entry.path), bytes)
  3687. @unittest.skipUnless(os.listdir in os.supports_fd,
  3688. 'fd support for listdir required for this test.')
  3689. def test_fd(self):
  3690. self.assertIn(os.scandir, os.supports_fd)
  3691. self.create_file('file.txt')
  3692. expected_names = ['file.txt']
  3693. if os_helper.can_symlink():
  3694. os.symlink('file.txt', os.path.join(self.path, 'link'))
  3695. expected_names.append('link')
  3696. with os_helper.open_dir_fd(self.path) as fd:
  3697. with os.scandir(fd) as it:
  3698. entries = list(it)
  3699. names = [entry.name for entry in entries]
  3700. self.assertEqual(sorted(names), expected_names)
  3701. self.assertEqual(names, os.listdir(fd))
  3702. for entry in entries:
  3703. self.assertEqual(entry.path, entry.name)
  3704. self.assertEqual(os.fspath(entry), entry.name)
  3705. self.assertEqual(entry.is_symlink(), entry.name == 'link')
  3706. if os.stat in os.supports_dir_fd:
  3707. st = os.stat(entry.name, dir_fd=fd)
  3708. self.assertEqual(entry.stat(), st)
  3709. st = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
  3710. self.assertEqual(entry.stat(follow_symlinks=False), st)
  3711. @unittest.skipIf(support.is_wasi, "WASI maps '' to cwd")
  3712. def test_empty_path(self):
  3713. self.assertRaises(FileNotFoundError, os.scandir, '')
  3714. def test_consume_iterator_twice(self):
  3715. self.create_file("file.txt")
  3716. iterator = os.scandir(self.path)
  3717. entries = list(iterator)
  3718. self.assertEqual(len(entries), 1, entries)
  3719. # check than consuming the iterator twice doesn't raise exception
  3720. entries2 = list(iterator)
  3721. self.assertEqual(len(entries2), 0, entries2)
  3722. def test_bad_path_type(self):
  3723. for obj in [1.234, {}, []]:
  3724. self.assertRaises(TypeError, os.scandir, obj)
  3725. def test_close(self):
  3726. self.create_file("file.txt")
  3727. self.create_file("file2.txt")
  3728. iterator = os.scandir(self.path)
  3729. next(iterator)
  3730. iterator.close()
  3731. # multiple closes
  3732. iterator.close()
  3733. with self.check_no_resource_warning():
  3734. del iterator
  3735. def test_context_manager(self):
  3736. self.create_file("file.txt")
  3737. self.create_file("file2.txt")
  3738. with os.scandir(self.path) as iterator:
  3739. next(iterator)
  3740. with self.check_no_resource_warning():
  3741. del iterator
  3742. def test_context_manager_close(self):
  3743. self.create_file("file.txt")
  3744. self.create_file("file2.txt")
  3745. with os.scandir(self.path) as iterator:
  3746. next(iterator)
  3747. iterator.close()
  3748. def test_context_manager_exception(self):
  3749. self.create_file("file.txt")
  3750. self.create_file("file2.txt")
  3751. with self.assertRaises(ZeroDivisionError):
  3752. with os.scandir(self.path) as iterator:
  3753. next(iterator)
  3754. 1/0
  3755. with self.check_no_resource_warning():
  3756. del iterator
  3757. def test_resource_warning(self):
  3758. self.create_file("file.txt")
  3759. self.create_file("file2.txt")
  3760. iterator = os.scandir(self.path)
  3761. next(iterator)
  3762. with self.assertWarns(ResourceWarning):
  3763. del iterator
  3764. support.gc_collect()
  3765. # exhausted iterator
  3766. iterator = os.scandir(self.path)
  3767. list(iterator)
  3768. with self.check_no_resource_warning():
  3769. del iterator
  3770. class TestPEP519(unittest.TestCase):
  3771. # Abstracted so it can be overridden to test pure Python implementation
  3772. # if a C version is provided.
  3773. fspath = staticmethod(os.fspath)
  3774. def test_return_bytes(self):
  3775. for b in b'hello', b'goodbye', b'some/path/and/file':
  3776. self.assertEqual(b, self.fspath(b))
  3777. def test_return_string(self):
  3778. for s in 'hello', 'goodbye', 'some/path/and/file':
  3779. self.assertEqual(s, self.fspath(s))
  3780. def test_fsencode_fsdecode(self):
  3781. for p in "path/like/object", b"path/like/object":
  3782. pathlike = FakePath(p)
  3783. self.assertEqual(p, self.fspath(pathlike))
  3784. self.assertEqual(b"path/like/object", os.fsencode(pathlike))
  3785. self.assertEqual("path/like/object", os.fsdecode(pathlike))
  3786. def test_pathlike(self):
  3787. self.assertEqual('#feelthegil', self.fspath(FakePath('#feelthegil')))
  3788. self.assertTrue(issubclass(FakePath, os.PathLike))
  3789. self.assertTrue(isinstance(FakePath('x'), os.PathLike))
  3790. def test_garbage_in_exception_out(self):
  3791. vapor = type('blah', (), {})
  3792. for o in int, type, os, vapor():
  3793. self.assertRaises(TypeError, self.fspath, o)
  3794. def test_argument_required(self):
  3795. self.assertRaises(TypeError, self.fspath)
  3796. def test_bad_pathlike(self):
  3797. # __fspath__ returns a value other than str or bytes.
  3798. self.assertRaises(TypeError, self.fspath, FakePath(42))
  3799. # __fspath__ attribute that is not callable.
  3800. c = type('foo', (), {})
  3801. c.__fspath__ = 1
  3802. self.assertRaises(TypeError, self.fspath, c())
  3803. # __fspath__ raises an exception.
  3804. self.assertRaises(ZeroDivisionError, self.fspath,
  3805. FakePath(ZeroDivisionError()))
  3806. def test_pathlike_subclasshook(self):
  3807. # bpo-38878: subclasshook causes subclass checks
  3808. # true on abstract implementation.
  3809. class A(os.PathLike):
  3810. pass
  3811. self.assertFalse(issubclass(FakePath, A))
  3812. self.assertTrue(issubclass(FakePath, os.PathLike))
  3813. def test_pathlike_class_getitem(self):
  3814. self.assertIsInstance(os.PathLike[bytes], types.GenericAlias)
  3815. class TimesTests(unittest.TestCase):
  3816. def test_times(self):
  3817. times = os.times()
  3818. self.assertIsInstance(times, os.times_result)
  3819. for field in ('user', 'system', 'children_user', 'children_system',
  3820. 'elapsed'):
  3821. value = getattr(times, field)
  3822. self.assertIsInstance(value, float)
  3823. if os.name == 'nt':
  3824. self.assertEqual(times.children_user, 0)
  3825. self.assertEqual(times.children_system, 0)
  3826. self.assertEqual(times.elapsed, 0)
  3827. @support.requires_fork()
  3828. class ForkTests(unittest.TestCase):
  3829. def test_fork(self):
  3830. # bpo-42540: ensure os.fork() with non-default memory allocator does
  3831. # not crash on exit.
  3832. code = """if 1:
  3833. import os
  3834. from test import support
  3835. pid = os.fork()
  3836. if pid != 0:
  3837. support.wait_process(pid, exitcode=0)
  3838. """
  3839. assert_python_ok("-c", code)
  3840. assert_python_ok("-c", code, PYTHONMALLOC="malloc_debug")
  3841. # Only test if the C version is provided, otherwise TestPEP519 already tested
  3842. # the pure Python implementation.
  3843. if hasattr(os, "_fspath"):
  3844. class TestPEP519PurePython(TestPEP519):
  3845. """Explicitly test the pure Python implementation of os.fspath()."""
  3846. fspath = staticmethod(os._fspath)
  3847. if __name__ == "__main__":
  3848. unittest.main()