Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

test_datasets_utils.py 10 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
  1. import contextlib
  2. import gzip
  3. import os
  4. import pathlib
  5. import re
  6. import tarfile
  7. import zipfile
  8. import pytest
  9. import torch
  10. import torchvision.datasets.utils as utils
  11. from common_utils import assert_equal
  12. from torch._utils_internal import get_file_path_2
  13. from torchvision.datasets.folder import make_dataset
  14. from torchvision.datasets.utils import _COMPRESSED_FILE_OPENERS
  15. TEST_FILE = get_file_path_2(
  16. os.path.dirname(os.path.abspath(__file__)), "assets", "encode_jpeg", "grace_hopper_517x606.jpg"
  17. )
  18. def patch_url_redirection(mocker, redirect_url):
  19. class Response:
  20. def __init__(self, url):
  21. self.url = url
  22. @contextlib.contextmanager
  23. def patched_opener(*args, **kwargs):
  24. yield Response(redirect_url)
  25. return mocker.patch("torchvision.datasets.utils.urllib.request.urlopen", side_effect=patched_opener)
  26. class TestDatasetsUtils:
  27. def test_get_redirect_url(self, mocker):
  28. url = "https://url.org"
  29. expected_redirect_url = "https://redirect.url.org"
  30. mock = patch_url_redirection(mocker, expected_redirect_url)
  31. actual = utils._get_redirect_url(url)
  32. assert actual == expected_redirect_url
  33. assert mock.call_count == 2
  34. call_args_1, call_args_2 = mock.call_args_list
  35. assert call_args_1[0][0].full_url == url
  36. assert call_args_2[0][0].full_url == expected_redirect_url
  37. def test_get_redirect_url_max_hops_exceeded(self, mocker):
  38. url = "https://url.org"
  39. redirect_url = "https://redirect.url.org"
  40. mock = patch_url_redirection(mocker, redirect_url)
  41. with pytest.raises(RecursionError):
  42. utils._get_redirect_url(url, max_hops=0)
  43. assert mock.call_count == 1
  44. assert mock.call_args[0][0].full_url == url
  45. @pytest.mark.parametrize("use_pathlib", (True, False))
  46. def test_check_md5(self, use_pathlib):
  47. fpath = TEST_FILE
  48. if use_pathlib:
  49. fpath = pathlib.Path(fpath)
  50. correct_md5 = "9c0bb82894bb3af7f7675ef2b3b6dcdc"
  51. false_md5 = ""
  52. assert utils.check_md5(fpath, correct_md5)
  53. assert not utils.check_md5(fpath, false_md5)
  54. def test_check_integrity(self):
  55. existing_fpath = TEST_FILE
  56. nonexisting_fpath = ""
  57. correct_md5 = "9c0bb82894bb3af7f7675ef2b3b6dcdc"
  58. false_md5 = ""
  59. assert utils.check_integrity(existing_fpath, correct_md5)
  60. assert not utils.check_integrity(existing_fpath, false_md5)
  61. assert utils.check_integrity(existing_fpath)
  62. assert not utils.check_integrity(nonexisting_fpath)
  63. def test_get_google_drive_file_id(self):
  64. url = "https://drive.google.com/file/d/1GO-BHUYRuvzr1Gtp2_fqXRsr9TIeYbhV/view"
  65. expected = "1GO-BHUYRuvzr1Gtp2_fqXRsr9TIeYbhV"
  66. actual = utils._get_google_drive_file_id(url)
  67. assert actual == expected
  68. def test_get_google_drive_file_id_invalid_url(self):
  69. url = "http://www.vision.caltech.edu/visipedia-data/CUB-200-2011/CUB_200_2011.tgz"
  70. assert utils._get_google_drive_file_id(url) is None
  71. @pytest.mark.parametrize(
  72. "file, expected",
  73. [
  74. ("foo.tar.bz2", (".tar.bz2", ".tar", ".bz2")),
  75. ("foo.tar.xz", (".tar.xz", ".tar", ".xz")),
  76. ("foo.tar", (".tar", ".tar", None)),
  77. ("foo.tar.gz", (".tar.gz", ".tar", ".gz")),
  78. ("foo.tbz", (".tbz", ".tar", ".bz2")),
  79. ("foo.tbz2", (".tbz2", ".tar", ".bz2")),
  80. ("foo.tgz", (".tgz", ".tar", ".gz")),
  81. ("foo.bz2", (".bz2", None, ".bz2")),
  82. ("foo.gz", (".gz", None, ".gz")),
  83. ("foo.zip", (".zip", ".zip", None)),
  84. ("foo.xz", (".xz", None, ".xz")),
  85. ("foo.bar.tar.gz", (".tar.gz", ".tar", ".gz")),
  86. ("foo.bar.gz", (".gz", None, ".gz")),
  87. ("foo.bar.zip", (".zip", ".zip", None)),
  88. ],
  89. )
  90. def test_detect_file_type(self, file, expected):
  91. assert utils._detect_file_type(file) == expected
  92. @pytest.mark.parametrize("file", ["foo", "foo.tar.baz", "foo.bar"])
  93. def test_detect_file_type_incompatible(self, file):
  94. # tests detect file type for no extension, unknown compression and unknown partial extension
  95. with pytest.raises(RuntimeError):
  96. utils._detect_file_type(file)
  97. @pytest.mark.parametrize("extension", [".bz2", ".gz", ".xz"])
  98. @pytest.mark.parametrize("use_pathlib", (True, False))
  99. def test_decompress(self, extension, tmpdir, use_pathlib):
  100. def create_compressed(root, content="this is the content"):
  101. file = os.path.join(root, "file")
  102. compressed = f"{file}{extension}"
  103. compressed_file_opener = _COMPRESSED_FILE_OPENERS[extension]
  104. with compressed_file_opener(compressed, "wb") as fh:
  105. fh.write(content.encode())
  106. return compressed, file, content
  107. compressed, file, content = create_compressed(tmpdir)
  108. if use_pathlib:
  109. compressed = pathlib.Path(compressed)
  110. utils._decompress(compressed)
  111. assert os.path.exists(file)
  112. with open(file) as fh:
  113. assert fh.read() == content
  114. def test_decompress_no_compression(self):
  115. with pytest.raises(RuntimeError):
  116. utils._decompress("foo.tar")
  117. @pytest.mark.parametrize("use_pathlib", (True, False))
  118. def test_decompress_remove_finished(self, tmpdir, use_pathlib):
  119. def create_compressed(root, content="this is the content"):
  120. file = os.path.join(root, "file")
  121. compressed = f"{file}.gz"
  122. with gzip.open(compressed, "wb") as fh:
  123. fh.write(content.encode())
  124. return compressed, file, content
  125. compressed, file, content = create_compressed(tmpdir)
  126. print(f"{type(compressed)=}")
  127. if use_pathlib:
  128. compressed = pathlib.Path(compressed)
  129. tmpdir = pathlib.Path(tmpdir)
  130. extracted_dir = utils.extract_archive(compressed, tmpdir, remove_finished=True)
  131. assert not os.path.exists(compressed)
  132. if use_pathlib:
  133. assert isinstance(extracted_dir, pathlib.Path)
  134. assert isinstance(compressed, pathlib.Path)
  135. else:
  136. assert isinstance(extracted_dir, str)
  137. assert isinstance(compressed, str)
  138. @pytest.mark.parametrize("extension", [".gz", ".xz"])
  139. @pytest.mark.parametrize("remove_finished", [True, False])
  140. def test_extract_archive_defer_to_decompress(self, extension, remove_finished, mocker):
  141. filename = "foo"
  142. file = f"{filename}{extension}"
  143. mocked = mocker.patch("torchvision.datasets.utils._decompress")
  144. utils.extract_archive(file, remove_finished=remove_finished)
  145. mocked.assert_called_once_with(file, filename, remove_finished=remove_finished)
  146. @pytest.mark.parametrize("use_pathlib", (True, False))
  147. def test_extract_zip(self, tmpdir, use_pathlib):
  148. def create_archive(root, content="this is the content"):
  149. file = os.path.join(root, "dst.txt")
  150. archive = os.path.join(root, "archive.zip")
  151. with zipfile.ZipFile(archive, "w") as zf:
  152. zf.writestr(os.path.basename(file), content)
  153. return archive, file, content
  154. if use_pathlib:
  155. tmpdir = pathlib.Path(tmpdir)
  156. archive, file, content = create_archive(tmpdir)
  157. utils.extract_archive(archive, tmpdir)
  158. assert os.path.exists(file)
  159. with open(file) as fh:
  160. assert fh.read() == content
  161. @pytest.mark.parametrize(
  162. "extension, mode", [(".tar", "w"), (".tar.gz", "w:gz"), (".tgz", "w:gz"), (".tar.xz", "w:xz")]
  163. )
  164. @pytest.mark.parametrize("use_pathlib", (True, False))
  165. def test_extract_tar(self, extension, mode, tmpdir, use_pathlib):
  166. def create_archive(root, extension, mode, content="this is the content"):
  167. src = os.path.join(root, "src.txt")
  168. dst = os.path.join(root, "dst.txt")
  169. archive = os.path.join(root, f"archive{extension}")
  170. with open(src, "w") as fh:
  171. fh.write(content)
  172. with tarfile.open(archive, mode=mode) as fh:
  173. fh.add(src, arcname=os.path.basename(dst))
  174. return archive, dst, content
  175. if use_pathlib:
  176. tmpdir = pathlib.Path(tmpdir)
  177. archive, file, content = create_archive(tmpdir, extension, mode)
  178. utils.extract_archive(archive, tmpdir)
  179. assert os.path.exists(file)
  180. with open(file) as fh:
  181. assert fh.read() == content
  182. def test_verify_str_arg(self):
  183. assert "a" == utils.verify_str_arg("a", "arg", ("a",))
  184. pytest.raises(ValueError, utils.verify_str_arg, 0, ("a",), "arg")
  185. pytest.raises(ValueError, utils.verify_str_arg, "b", ("a",), "arg")
  186. @pytest.mark.parametrize(
  187. ("dtype", "actual_hex", "expected_hex"),
  188. [
  189. (torch.uint8, "01 23 45 67 89 AB CD EF", "01 23 45 67 89 AB CD EF"),
  190. (torch.float16, "01 23 45 67 89 AB CD EF", "23 01 67 45 AB 89 EF CD"),
  191. (torch.int32, "01 23 45 67 89 AB CD EF", "67 45 23 01 EF CD AB 89"),
  192. (torch.float64, "01 23 45 67 89 AB CD EF", "EF CD AB 89 67 45 23 01"),
  193. ],
  194. )
  195. def test_flip_byte_order(self, dtype, actual_hex, expected_hex):
  196. def to_tensor(hex):
  197. return torch.frombuffer(bytes.fromhex(hex), dtype=dtype)
  198. assert_equal(
  199. utils._flip_byte_order(to_tensor(actual_hex)),
  200. to_tensor(expected_hex),
  201. )
  202. @pytest.mark.parametrize(
  203. ("kwargs", "expected_error_msg"),
  204. [
  205. (dict(is_valid_file=lambda path: pathlib.Path(path).suffix in {".png", ".jpeg"}), "classes c"),
  206. (dict(extensions=".png"), re.escape("classes b, c. Supported extensions are: .png")),
  207. (dict(extensions=(".png", ".jpeg")), re.escape("classes c. Supported extensions are: .png, .jpeg")),
  208. ],
  209. )
  210. def test_make_dataset_no_valid_files(tmpdir, kwargs, expected_error_msg):
  211. tmpdir = pathlib.Path(tmpdir)
  212. (tmpdir / "a").mkdir()
  213. (tmpdir / "a" / "a.png").touch()
  214. (tmpdir / "b").mkdir()
  215. (tmpdir / "b" / "b.jpeg").touch()
  216. (tmpdir / "c").mkdir()
  217. (tmpdir / "c" / "c.unknown").touch()
  218. with pytest.raises(FileNotFoundError, match=expected_error_msg):
  219. make_dataset(str(tmpdir), **kwargs)
  220. if __name__ == "__main__":
  221. pytest.main([__file__])
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...