|
2 | 2 |
|
3 | 3 | from __future__ import division, print_function, unicode_literals |
4 | 4 | import io |
| 5 | +import sys |
| 6 | +import json |
5 | 7 |
|
6 | 8 | import libarchive |
7 | 9 | from libarchive.extract import EXTRACT_OWNER, EXTRACT_PERM, EXTRACT_TIME |
8 | 10 | from libarchive.write import memory_writer |
9 | 11 | from mock import patch |
10 | 12 |
|
| 13 | +import pytest |
| 14 | + |
11 | 15 | from . import check_archive, in_dir, treestat |
12 | 16 |
|
13 | 17 |
|
@@ -115,24 +119,45 @@ def test_write_not_fail(write_fail_mock): |
115 | 119 | assert not write_fail_mock.called |
116 | 120 |
|
117 | 121 |
|
118 | | -def test_adding_entry_from_memory(): |
119 | | - entry_path = 'this is path' |
120 | | - entry_data = 'content' |
121 | | - entry_size = len(entry_data) |
| 122 | +@pytest.mark.parametrize( |
| 123 | + 'archfmt,data_bytes', |
| 124 | + [('zip', b'content'), |
| 125 | + ('gnutar', 'a_string'.encode()), |
| 126 | + ('pax', json.dumps({'a': 1, 'b': 2, 'c': 3}).encode())]) |
| 127 | +def test_adding_entry_from_memory(archfmt, data_bytes): |
| 128 | + if sys.version_info[0] < 3: |
| 129 | + string_types = (str, unicode) # noqa: F821 |
| 130 | + else: |
| 131 | + string_types = (str,) |
| 132 | + |
| 133 | + entry_path = 'testfile.data' |
| 134 | + |
| 135 | + # entry_data must be a list of byte-like objects for maximum compatibility |
| 136 | + # (Use of other data types can have undesirable side-effects) |
| 137 | + # entry_size is the total size in bytes of the entry_data items |
| 138 | + entry_data = [data_bytes] |
| 139 | + entry_size = sum(len(bdata) for bdata in entry_data) |
122 | 140 |
|
123 | 141 | blocks = [] |
124 | 142 |
|
125 | 143 | def write_callback(data): |
126 | 144 | blocks.append(data[:]) |
127 | 145 | return len(data) |
128 | 146 |
|
129 | | - with libarchive.custom_writer(write_callback, 'zip') as archive: |
130 | | - archive.add_file_from_memory(entry_path, entry_size, entry_data) |
| 147 | + with libarchive.custom_writer(write_callback, archfmt) as archive: |
| 148 | + archive.add_file_from_memory( |
| 149 | + entry_path, entry_size, entry_data) |
131 | 150 |
|
132 | 151 | buf = b''.join(blocks) |
133 | 152 | with libarchive.memory_reader(buf) as memory_archive: |
134 | 153 | for archive_entry in memory_archive: |
135 | | - assert entry_data.encode() == b''.join( |
136 | | - archive_entry.get_blocks() |
| 154 | + expected = b''.join( |
| 155 | + [a.encode() |
| 156 | + if isinstance(a, string_types) |
| 157 | + else a for a in entry_data], |
| 158 | + ) |
| 159 | + actual = b''.join( |
| 160 | + archive_entry.get_blocks(), |
137 | 161 | ) |
| 162 | + assert expected == actual |
138 | 163 | assert archive_entry.path == entry_path |
0 commit comments