test_mock.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Tests for our mock_open helper
  4. '''
  5. # Import Python Libs
  6. from __future__ import absolute_import, unicode_literals, print_function
  7. import errno
  8. import logging
  9. import textwrap
  10. # Import Salt libs
  11. import salt.utils.data
  12. import salt.utils.files
  13. import salt.utils.stringutils
  14. from salt.ext import six
  15. # Import Salt Testing Libs
  16. from tests.support.mock import patch, mock_open
  17. from tests.support.unit import TestCase
  18. log = logging.getLogger(__name__)
  19. class MockOpenMixin(object):
  20. def _get_values(self, binary=False, multifile=False, split=False):
  21. if split:
  22. questions = (self.questions_bytes_lines if binary
  23. else self.questions_str_lines)
  24. answers = (self.answers_bytes_lines if binary
  25. else self.answers_str_lines)
  26. else:
  27. questions = self.questions_bytes if binary else self.questions_str
  28. answers = self.answers_bytes if binary else self.answers_str
  29. mode = 'rb' if binary else 'r'
  30. if multifile:
  31. read_data = self.contents_bytes if binary else self.contents
  32. else:
  33. read_data = self.questions_bytes if binary else self.questions
  34. return questions, answers, mode, read_data
  35. def _test_read(self, binary=False, multifile=False):
  36. questions, answers, mode, read_data = \
  37. self._get_values(binary=binary, multifile=multifile)
  38. with patch('salt.utils.files.fopen', mock_open(read_data=read_data)):
  39. with salt.utils.files.fopen('foo.txt', mode) as self.fh:
  40. result = self.fh.read()
  41. assert result == questions, result
  42. if multifile:
  43. with salt.utils.files.fopen('bar.txt', mode) as self.fh2:
  44. result = self.fh2.read()
  45. assert result == answers, result
  46. with salt.utils.files.fopen('baz.txt', mode) as self.fh3:
  47. result = self.fh3.read()
  48. assert result == answers, result
  49. try:
  50. with salt.utils.files.fopen('helloworld.txt'):
  51. raise Exception('No patterns should have matched')
  52. except IOError:
  53. # An IOError is expected here
  54. pass
  55. def _test_read_explicit_size(self, binary=False, multifile=False):
  56. questions, answers, mode, read_data = \
  57. self._get_values(binary=binary, multifile=multifile)
  58. with patch('salt.utils.files.fopen', mock_open(read_data=read_data)):
  59. with salt.utils.files.fopen('foo.txt', mode) as self.fh:
  60. # Read 10 bytes
  61. result = self.fh.read(10)
  62. assert result == questions[:10], result
  63. # Read another 10 bytes
  64. result = self.fh.read(10)
  65. assert result == questions[10:20], result
  66. # Read the rest
  67. result = self.fh.read()
  68. assert result == questions[20:], result
  69. if multifile:
  70. with salt.utils.files.fopen('bar.txt', mode) as self.fh2:
  71. # Read 10 bytes
  72. result = self.fh2.read(10)
  73. assert result == answers[:10], result
  74. # Read another 10 bytes
  75. result = self.fh2.read(10)
  76. assert result == answers[10:20], result
  77. # Read the rest
  78. result = self.fh2.read()
  79. assert result == answers[20:], result
  80. with salt.utils.files.fopen('baz.txt', mode) as self.fh3:
  81. # Read 10 bytes
  82. result = self.fh3.read(10)
  83. assert result == answers[:10], result
  84. # Read another 10 bytes
  85. result = self.fh3.read(10)
  86. assert result == answers[10:20], result
  87. # Read the rest
  88. result = self.fh3.read()
  89. assert result == answers[20:], result
  90. try:
  91. with salt.utils.files.fopen('helloworld.txt'):
  92. raise Exception('No globs should have matched')
  93. except IOError:
  94. # An IOError is expected here
  95. pass
  96. def _test_read_explicit_size_larger_than_file_size(self,
  97. binary=False,
  98. multifile=False):
  99. questions, answers, mode, read_data = \
  100. self._get_values(binary=binary, multifile=multifile)
  101. with patch('salt.utils.files.fopen', mock_open(read_data=read_data)):
  102. with salt.utils.files.fopen('foo.txt', mode) as self.fh:
  103. result = self.fh.read(999999)
  104. assert result == questions, result
  105. if multifile:
  106. with salt.utils.files.fopen('bar.txt', mode) as self.fh2:
  107. result = self.fh2.read(999999)
  108. assert result == answers, result
  109. with salt.utils.files.fopen('baz.txt', mode) as self.fh3:
  110. result = self.fh3.read(999999)
  111. assert result == answers, result
  112. try:
  113. with salt.utils.files.fopen('helloworld.txt'):
  114. raise Exception('No globs should have matched')
  115. except IOError:
  116. # An IOError is expected here
  117. pass
  118. def _test_read_for_loop(self, binary=False, multifile=False):
  119. questions, answers, mode, read_data = \
  120. self._get_values(binary=binary, multifile=multifile, split=True)
  121. with patch('salt.utils.files.fopen', mock_open(read_data=read_data)):
  122. with salt.utils.files.fopen('foo.txt', mode) as self.fh:
  123. index = 0
  124. for line in self.fh:
  125. assert line == questions[index], \
  126. 'Line {0}: {1}'.format(index, line)
  127. index += 1
  128. if multifile:
  129. with salt.utils.files.fopen('bar.txt', mode) as self.fh2:
  130. index = 0
  131. for line in self.fh2:
  132. assert line == answers[index], \
  133. 'Line {0}: {1}'.format(index, line)
  134. index += 1
  135. with salt.utils.files.fopen('baz.txt', mode) as self.fh3:
  136. index = 0
  137. for line in self.fh3:
  138. assert line == answers[index], \
  139. 'Line {0}: {1}'.format(index, line)
  140. index += 1
  141. try:
  142. with salt.utils.files.fopen('helloworld.txt'):
  143. raise Exception('No globs should have matched')
  144. except IOError:
  145. # An IOError is expected here
  146. pass
  147. def _test_read_readline(self, binary=False, multifile=False):
  148. questions, answers, mode, read_data = \
  149. self._get_values(binary=binary, multifile=multifile, split=True)
  150. with patch('salt.utils.files.fopen', mock_open(read_data=read_data)):
  151. with salt.utils.files.fopen('foo.txt', mode) as self.fh:
  152. size = 8
  153. result = self.fh.read(size)
  154. assert result == questions[0][:size], result
  155. # Use .readline() to read the remainder of the line
  156. result = self.fh.readline()
  157. assert result == questions[0][size:], result
  158. # Read and check the other two lines
  159. result = self.fh.readline()
  160. assert result == questions[1], result
  161. result = self.fh.readline()
  162. assert result == questions[2], result
  163. if multifile:
  164. with salt.utils.files.fopen('bar.txt', mode) as self.fh2:
  165. size = 20
  166. result = self.fh2.read(size)
  167. assert result == answers[0][:size], result
  168. # Use .readline() to read the remainder of the line
  169. result = self.fh2.readline()
  170. assert result == answers[0][size:], result
  171. # Read and check the other two lines
  172. result = self.fh2.readline()
  173. assert result == answers[1], result
  174. result = self.fh2.readline()
  175. assert result == answers[2], result
  176. with salt.utils.files.fopen('baz.txt', mode) as self.fh3:
  177. size = 20
  178. result = self.fh3.read(size)
  179. assert result == answers[0][:size], result
  180. # Use .readline() to read the remainder of the line
  181. result = self.fh3.readline()
  182. assert result == answers[0][size:], result
  183. # Read and check the other two lines
  184. result = self.fh3.readline()
  185. assert result == answers[1], result
  186. result = self.fh3.readline()
  187. assert result == answers[2], result
  188. try:
  189. with salt.utils.files.fopen('helloworld.txt'):
  190. raise Exception('No globs should have matched')
  191. except IOError:
  192. # An IOError is expected here
  193. pass
  194. def _test_readline_readlines(self, binary=False, multifile=False):
  195. questions, answers, mode, read_data = \
  196. self._get_values(binary=binary, multifile=multifile, split=True)
  197. with patch('salt.utils.files.fopen', mock_open(read_data=read_data)):
  198. with salt.utils.files.fopen('foo.txt', mode) as self.fh:
  199. # Read the first line
  200. result = self.fh.readline()
  201. assert result == questions[0], result
  202. # Use .readlines() to read the remainder of the file
  203. result = self.fh.readlines()
  204. assert result == questions[1:], result
  205. if multifile:
  206. with salt.utils.files.fopen('bar.txt', mode) as self.fh2:
  207. # Read the first line
  208. result = self.fh2.readline()
  209. assert result == answers[0], result
  210. # Use .readlines() to read the remainder of the file
  211. result = self.fh2.readlines()
  212. assert result == answers[1:], result
  213. with salt.utils.files.fopen('baz.txt', mode) as self.fh3:
  214. # Read the first line
  215. result = self.fh3.readline()
  216. assert result == answers[0], result
  217. # Use .readlines() to read the remainder of the file
  218. result = self.fh3.readlines()
  219. assert result == answers[1:], result
  220. try:
  221. with salt.utils.files.fopen('helloworld.txt'):
  222. raise Exception('No globs should have matched')
  223. except IOError:
  224. # An IOError is expected here
  225. pass
  226. def _test_readlines_multifile(self, binary=False, multifile=False):
  227. questions, answers, mode, read_data = \
  228. self._get_values(binary=binary, multifile=multifile, split=True)
  229. with patch('salt.utils.files.fopen', mock_open(read_data=read_data)):
  230. with salt.utils.files.fopen('foo.txt', mode) as self.fh:
  231. result = self.fh.readlines()
  232. assert result == questions, result
  233. if multifile:
  234. with salt.utils.files.fopen('bar.txt', mode) as self.fh2:
  235. result = self.fh2.readlines()
  236. assert result == answers, result
  237. with salt.utils.files.fopen('baz.txt', mode) as self.fh3:
  238. result = self.fh3.readlines()
  239. assert result == answers, result
  240. try:
  241. with salt.utils.files.fopen('helloworld.txt'):
  242. raise Exception('No globs should have matched')
  243. except IOError:
  244. # An IOError is expected here
  245. pass
  246. class MockOpenTestCase(TestCase, MockOpenMixin):
  247. '''
  248. Tests for our mock_open helper to ensure that it behaves as closely as
  249. possible to a real filehandle.
  250. '''
  251. # Cyrllic characters used to test unicode handling
  252. questions = textwrap.dedent('''\
  253. Шнат is your name?
  254. Шнат is your quest?
  255. Шнат is the airspeed velocity of an unladen swallow?
  256. ''')
  257. answers = textwrap.dedent('''\
  258. It is Аятнця, King of the Britons.
  259. To seek тне Holy Grail.
  260. Шнат do you mean? An African or European swallow?
  261. ''')
  262. @classmethod
  263. def setUpClass(cls):
  264. cls.questions_lines = cls.questions.splitlines(True)
  265. cls.answers_lines = cls.answers.splitlines(True)
  266. cls.questions_str = salt.utils.stringutils.to_str(cls.questions)
  267. cls.answers_str = salt.utils.stringutils.to_str(cls.answers)
  268. cls.questions_str_lines = cls.questions_str.splitlines(True)
  269. cls.answers_str_lines = cls.answers_str.splitlines(True)
  270. cls.questions_bytes = salt.utils.stringutils.to_bytes(cls.questions)
  271. cls.answers_bytes = salt.utils.stringutils.to_bytes(cls.answers)
  272. cls.questions_bytes_lines = cls.questions_bytes.splitlines(True)
  273. cls.answers_bytes_lines = cls.answers_bytes.splitlines(True)
  274. # When this is used as the read_data, Python 2 should normalize
  275. # cls.questions and cls.answers to str types.
  276. cls.contents = {'foo.txt': cls.questions,
  277. 'b*.txt': cls.answers}
  278. cls.contents_bytes = {'foo.txt': cls.questions_bytes,
  279. 'b*.txt': cls.answers_bytes}
  280. cls.read_data_as_list = [
  281. 'foo', 'bar', 'спам',
  282. IOError(errno.EACCES, 'Permission denied')
  283. ]
  284. cls.normalized_read_data_as_list = salt.utils.data.decode(
  285. cls.read_data_as_list,
  286. to_str=True
  287. )
  288. cls.read_data_as_list_bytes = salt.utils.data.encode(cls.read_data_as_list)
  289. def tearDown(self):
  290. '''
  291. Each test should read the entire contents of the mocked filehandle(s).
  292. This confirms that the other read functions return empty strings/lists,
  293. to simulate being at EOF.
  294. '''
  295. for handle_name in ('fh', 'fh2', 'fh3'):
  296. try:
  297. fh = getattr(self, handle_name)
  298. except AttributeError:
  299. continue
  300. log.debug('Running tearDown tests for self.%s', handle_name)
  301. try:
  302. result = fh.read(5)
  303. assert not result, result
  304. result = fh.read()
  305. assert not result, result
  306. result = fh.readline()
  307. assert not result, result
  308. result = fh.readlines()
  309. assert not result, result
  310. # Last but not least, try to read using a for loop. This should not
  311. # read anything as we should hit EOF immediately, before the generator
  312. # in the mocked filehandle has a chance to yield anything. So the
  313. # exception will only be raised if we aren't at EOF already.
  314. for line in fh:
  315. raise Exception(
  316. 'Instead of EOF, read the following from {0}: {1}'.format(
  317. handle_name,
  318. line
  319. )
  320. )
  321. except IOError as exc:
  322. if six.text_type(exc) != 'File not open for reading':
  323. raise
  324. del fh
  325. def test_read(self):
  326. '''
  327. Test reading the entire file
  328. '''
  329. self._test_read(binary=False, multifile=False)
  330. self._test_read(binary=True, multifile=False)
  331. self._test_read(binary=False, multifile=True)
  332. self._test_read(binary=True, multifile=True)
  333. def test_read_explicit_size(self):
  334. '''
  335. Test reading with explicit sizes
  336. '''
  337. self._test_read_explicit_size(binary=False, multifile=False)
  338. self._test_read_explicit_size(binary=True, multifile=False)
  339. self._test_read_explicit_size(binary=False, multifile=True)
  340. self._test_read_explicit_size(binary=True, multifile=True)
  341. def test_read_explicit_size_larger_than_file_size(self):
  342. '''
  343. Test reading with an explicit size larger than the size of read_data.
  344. This ensures that we just return the contents up until EOF and that we
  345. don't raise any errors due to the desired size being larger than the
  346. mocked file's size.
  347. '''
  348. self._test_read_explicit_size_larger_than_file_size(
  349. binary=False, multifile=False)
  350. self._test_read_explicit_size_larger_than_file_size(
  351. binary=True, multifile=False)
  352. self._test_read_explicit_size_larger_than_file_size(
  353. binary=False, multifile=True)
  354. self._test_read_explicit_size_larger_than_file_size(
  355. binary=True, multifile=True)
  356. def test_read_for_loop(self):
  357. '''
  358. Test reading the contents of the file line by line in a for loop
  359. '''
  360. self._test_read_for_loop(binary=False, multifile=False)
  361. self._test_read_for_loop(binary=True, multifile=False)
  362. self._test_read_for_loop(binary=False, multifile=True)
  363. self._test_read_for_loop(binary=True, multifile=True)
  364. def test_read_readline(self):
  365. '''
  366. Test reading part of a line using .read(), then reading the rest of the
  367. line (and subsequent lines) using .readline().
  368. '''
  369. self._test_read_readline(binary=False, multifile=False)
  370. self._test_read_readline(binary=True, multifile=False)
  371. self._test_read_readline(binary=False, multifile=True)
  372. self._test_read_readline(binary=True, multifile=True)
  373. def test_readline_readlines(self):
  374. '''
  375. Test reading the first line using .readline(), then reading the rest of
  376. the file using .readlines().
  377. '''
  378. self._test_readline_readlines(binary=False, multifile=False)
  379. self._test_readline_readlines(binary=True, multifile=False)
  380. self._test_readline_readlines(binary=False, multifile=True)
  381. self._test_readline_readlines(binary=True, multifile=True)
  382. def test_readlines(self):
  383. '''
  384. Test reading the entire file using .readlines
  385. '''
  386. self._test_readlines_multifile(binary=False, multifile=False)
  387. self._test_readlines_multifile(binary=True, multifile=False)
  388. self._test_readlines_multifile(binary=False, multifile=True)
  389. self._test_readlines_multifile(binary=True, multifile=True)
  390. def test_read_data_converted_to_dict(self):
  391. '''
  392. Test that a non-dict value for read_data is converted to a dict mapping
  393. '*' to that value.
  394. '''
  395. contents = 'спам'
  396. normalized = salt.utils.stringutils.to_str(contents)
  397. with patch('salt.utils.files.fopen',
  398. mock_open(read_data=contents)) as m_open:
  399. assert m_open.read_data == {'*': normalized}, m_open.read_data
  400. with patch('salt.utils.files.fopen',
  401. mock_open(read_data=self.read_data_as_list)) as m_open:
  402. assert m_open.read_data == {
  403. '*': self.normalized_read_data_as_list,
  404. }, m_open.read_data
  405. def test_read_data_list(self):
  406. '''
  407. Test read_data when it is a list
  408. '''
  409. with patch('salt.utils.files.fopen',
  410. mock_open(read_data=self.read_data_as_list)):
  411. for value in self.normalized_read_data_as_list:
  412. try:
  413. with salt.utils.files.fopen('foo.txt') as self.fh:
  414. result = self.fh.read()
  415. assert result == value, result
  416. except IOError:
  417. # Only raise the caught exception if it wasn't expected
  418. # (i.e. if value is not an exception)
  419. if not isinstance(value, IOError):
  420. raise
  421. def test_read_data_list_bytes(self):
  422. '''
  423. Test read_data when it is a list and the value is a bytestring
  424. '''
  425. with patch('salt.utils.files.fopen',
  426. mock_open(read_data=self.read_data_as_list_bytes)):
  427. for value in self.read_data_as_list_bytes:
  428. try:
  429. with salt.utils.files.fopen('foo.txt', 'rb') as self.fh:
  430. result = self.fh.read()
  431. assert result == value, result
  432. except IOError:
  433. # Only raise the caught exception if it wasn't expected
  434. # (i.e. if value is not an exception)
  435. if not isinstance(value, IOError):
  436. raise
  437. def test_tell(self):
  438. '''
  439. Test the implementation of tell
  440. '''
  441. with patch('salt.utils.files.fopen',
  442. mock_open(read_data=self.contents)):
  443. # Try with reading explicit sizes and then reading the rest of the
  444. # file.
  445. with salt.utils.files.fopen('foo.txt') as self.fh:
  446. self.fh.read(5)
  447. loc = self.fh.tell()
  448. assert loc == 5, loc
  449. self.fh.read(12)
  450. loc = self.fh.tell()
  451. assert loc == 17, loc
  452. self.fh.read()
  453. loc = self.fh.tell()
  454. assert loc == len(self.questions_str), loc
  455. # Try reading way more content then actually exists in the file,
  456. # tell() should return a value equal to the length of the content
  457. with salt.utils.files.fopen('foo.txt') as self.fh:
  458. self.fh.read(999999)
  459. loc = self.fh.tell()
  460. assert loc == len(self.questions_str), loc
  461. # Try reading a few bytes using .read(), then the rest of the line
  462. # using .readline(), then the rest of the file using .readlines(),
  463. # and check the location after each read.
  464. with salt.utils.files.fopen('foo.txt') as self.fh:
  465. # Read a few bytes
  466. self.fh.read(5)
  467. loc = self.fh.tell()
  468. assert loc == 5, loc
  469. # Read the rest of the line. Location should then be at the end
  470. # of the first line.
  471. self.fh.readline()
  472. loc = self.fh.tell()
  473. assert loc == len(self.questions_str_lines[0]), loc
  474. # Read the rest of the file using .readlines()
  475. self.fh.readlines()
  476. loc = self.fh.tell()
  477. assert loc == len(self.questions_str), loc
  478. # Check location while iterating through the filehandle
  479. with salt.utils.files.fopen('foo.txt') as self.fh:
  480. index = 0
  481. for _ in self.fh:
  482. index += 1
  483. loc = self.fh.tell()
  484. assert loc == sum(
  485. len(x) for x in self.questions_str_lines[:index]
  486. ), loc
  487. def test_write(self):
  488. '''
  489. Test writing to a filehandle using .write()
  490. '''
  491. # Test opening for non-binary writing
  492. with patch('salt.utils.files.fopen', mock_open()):
  493. with salt.utils.files.fopen('foo.txt', 'w') as self.fh:
  494. for line in self.questions_str_lines:
  495. self.fh.write(line)
  496. assert self.fh.write_calls == self.questions_str_lines, self.fh.write_calls
  497. # Test opening for binary writing using "wb"
  498. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  499. with salt.utils.files.fopen('foo.txt', 'wb') as self.fh:
  500. for line in self.questions_bytes_lines:
  501. self.fh.write(line)
  502. assert self.fh.write_calls == self.questions_bytes_lines, self.fh.write_calls
  503. # Test opening for binary writing using "ab"
  504. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  505. with salt.utils.files.fopen('foo.txt', 'ab') as self.fh:
  506. for line in self.questions_bytes_lines:
  507. self.fh.write(line)
  508. assert self.fh.write_calls == self.questions_bytes_lines, self.fh.write_calls
  509. # Test opening for read-and-write using "r+b"
  510. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  511. with salt.utils.files.fopen('foo.txt', 'r+b') as self.fh:
  512. for line in self.questions_bytes_lines:
  513. self.fh.write(line)
  514. assert self.fh.write_calls == self.questions_bytes_lines, self.fh.write_calls
  515. # Test trying to write str types to a binary filehandle
  516. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  517. with salt.utils.files.fopen('foo.txt', 'wb') as self.fh:
  518. try:
  519. self.fh.write('foo\n')
  520. except TypeError:
  521. # This exception is expected on Python 3
  522. if not six.PY3:
  523. raise
  524. else:
  525. # This write should work fine on Python 2
  526. if six.PY3:
  527. raise Exception(
  528. 'Should not have been able to write a str to a '
  529. 'binary filehandle'
  530. )
  531. if six.PY2:
  532. # Try with non-ascii unicode. Note that the write above
  533. # should work because the mocked filehandle should attempt
  534. # a .encode() to convert it to a str type. But when writing
  535. # a string with non-ascii unicode, it should raise a
  536. # UnicodeEncodeError, which is what we are testing here.
  537. try:
  538. self.fh.write(self.questions)
  539. except UnicodeEncodeError:
  540. pass
  541. else:
  542. raise Exception(
  543. 'Should not have been able to write non-ascii '
  544. 'unicode to a binary filehandle'
  545. )
  546. # Test trying to write bytestrings to a non-binary filehandle
  547. with patch('salt.utils.files.fopen', mock_open()):
  548. with salt.utils.files.fopen('foo.txt', 'w') as self.fh:
  549. try:
  550. self.fh.write(b'foo\n')
  551. except TypeError:
  552. # This exception is expected on Python 3
  553. if not six.PY3:
  554. raise
  555. else:
  556. # This write should work fine on Python 2
  557. if six.PY3:
  558. raise Exception(
  559. 'Should not have been able to write a bytestring '
  560. 'to a non-binary filehandle'
  561. )
  562. if six.PY2:
  563. # Try with non-ascii unicode. Note that the write above
  564. # should work because the mocked filehandle should attempt
  565. # a .encode() to convert it to a str type. But when writing
  566. # a string with non-ascii unicode, it should raise a
  567. # UnicodeEncodeError, which is what we are testing here.
  568. try:
  569. self.fh.write(self.questions)
  570. except UnicodeEncodeError:
  571. pass
  572. else:
  573. raise Exception(
  574. 'Should not have been able to write non-ascii '
  575. 'unicode to a binary filehandle'
  576. )
  577. def test_writelines(self):
  578. '''
  579. Test writing to a filehandle using .writelines()
  580. '''
  581. # Test opening for non-binary writing
  582. with patch('salt.utils.files.fopen', mock_open()):
  583. with salt.utils.files.fopen('foo.txt', 'w') as self.fh:
  584. self.fh.writelines(self.questions_str_lines)
  585. assert self.fh.writelines_calls == [self.questions_str_lines], self.fh.writelines_calls
  586. # Test opening for binary writing using "wb"
  587. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  588. with salt.utils.files.fopen('foo.txt', 'wb') as self.fh:
  589. self.fh.writelines(self.questions_bytes_lines)
  590. assert self.fh.writelines_calls == [self.questions_bytes_lines], self.fh.writelines_calls
  591. # Test opening for binary writing using "ab"
  592. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  593. with salt.utils.files.fopen('foo.txt', 'ab') as self.fh:
  594. self.fh.writelines(self.questions_bytes_lines)
  595. assert self.fh.writelines_calls == [self.questions_bytes_lines], self.fh.writelines_calls
  596. # Test opening for read-and-write using "r+b"
  597. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  598. with salt.utils.files.fopen('foo.txt', 'r+b') as self.fh:
  599. self.fh.writelines(self.questions_bytes_lines)
  600. assert self.fh.writelines_calls == [self.questions_bytes_lines], self.fh.writelines_calls
  601. # Test trying to write str types to a binary filehandle
  602. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  603. with salt.utils.files.fopen('foo.txt', 'wb') as self.fh:
  604. try:
  605. self.fh.writelines(['foo\n'])
  606. except TypeError:
  607. # This exception is expected on Python 3
  608. if not six.PY3:
  609. raise
  610. else:
  611. # This write should work fine on Python 2
  612. if six.PY3:
  613. raise Exception(
  614. 'Should not have been able to write a str to a '
  615. 'binary filehandle'
  616. )
  617. if six.PY2:
  618. # Try with non-ascii unicode. Note that the write above
  619. # should work because the mocked filehandle should attempt
  620. # a .encode() to convert it to a str type. But when writing
  621. # a string with non-ascii unicode, it should raise a
  622. # UnicodeEncodeError, which is what we are testing here.
  623. try:
  624. self.fh.writelines(self.questions_lines)
  625. except UnicodeEncodeError:
  626. pass
  627. else:
  628. raise Exception(
  629. 'Should not have been able to write non-ascii '
  630. 'unicode to a binary filehandle'
  631. )
  632. # Test trying to write bytestrings to a non-binary filehandle
  633. with patch('salt.utils.files.fopen', mock_open()):
  634. with salt.utils.files.fopen('foo.txt', 'w') as self.fh:
  635. try:
  636. self.fh.write([b'foo\n'])
  637. except TypeError:
  638. # This exception is expected on Python 3
  639. if not six.PY3:
  640. raise
  641. else:
  642. # This write should work fine on Python 2
  643. if six.PY3:
  644. raise Exception(
  645. 'Should not have been able to write a bytestring '
  646. 'to a non-binary filehandle'
  647. )
  648. if six.PY2:
  649. # Try with non-ascii unicode. Note that the write above
  650. # should work because the mocked filehandle should attempt
  651. # a .encode() to convert it to a str type. But when writing
  652. # a string with non-ascii unicode, it should raise a
  653. # UnicodeEncodeError, which is what we are testing here.
  654. try:
  655. self.fh.writelines(self.questions_lines)
  656. except UnicodeEncodeError:
  657. pass
  658. else:
  659. raise Exception(
  660. 'Should not have been able to write non-ascii '
  661. 'unicode to a binary filehandle'
  662. )
  663. def test_open(self):
  664. '''
  665. Test that opening a file for binary reading with string read_data
  666. fails, and that the same thing happens for non-binary filehandles and
  667. bytestring read_data.
  668. NOTE: This test should always pass on PY2 since MockOpen will normalize
  669. unicode types to str types.
  670. '''
  671. try:
  672. with patch('salt.utils.files.fopen', mock_open()):
  673. try:
  674. with salt.utils.files.fopen('foo.txt', 'rb') as self.fh:
  675. self.fh.read()
  676. except TypeError:
  677. pass
  678. else:
  679. if six.PY3:
  680. raise Exception(
  681. 'Should not have been able open for binary read with '
  682. 'non-bytestring read_data'
  683. )
  684. with patch('salt.utils.files.fopen', mock_open(read_data=b'')):
  685. try:
  686. with salt.utils.files.fopen('foo.txt', 'r') as self.fh2:
  687. self.fh2.read()
  688. except TypeError:
  689. pass
  690. else:
  691. if six.PY3:
  692. raise Exception(
  693. 'Should not have been able open for non-binary read '
  694. 'with bytestring read_data'
  695. )
  696. finally:
  697. # Make sure we destroy the filehandles before the teardown, as they
  698. # will also try to read and this will generate another exception
  699. delattr(self, 'fh')
  700. delattr(self, 'fh2')