test_datasets_download.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import contextlib
  2. import itertools
  3. import tempfile
  4. import time
  5. import traceback
  6. import unittest.mock
  7. import warnings
  8. from datetime import datetime
  9. from distutils import dir_util
  10. from os import path
  11. from urllib.error import HTTPError, URLError
  12. from urllib.parse import urlparse
  13. from urllib.request import Request, urlopen
  14. import pytest
  15. from torchvision import datasets
  16. from torchvision.datasets.utils import _get_redirect_url, USER_AGENT
  17. def limit_requests_per_time(min_secs_between_requests=2.0):
  18. last_requests = {}
  19. def outer_wrapper(fn):
  20. def inner_wrapper(request, *args, **kwargs):
  21. url = request.full_url if isinstance(request, Request) else request
  22. netloc = urlparse(url).netloc
  23. last_request = last_requests.get(netloc)
  24. if last_request is not None:
  25. elapsed_secs = (datetime.now() - last_request).total_seconds()
  26. delta = min_secs_between_requests - elapsed_secs
  27. if delta > 0:
  28. time.sleep(delta)
  29. response = fn(request, *args, **kwargs)
  30. last_requests[netloc] = datetime.now()
  31. return response
  32. return inner_wrapper
  33. return outer_wrapper
  34. urlopen = limit_requests_per_time()(urlopen)
  35. def resolve_redirects(max_hops=3):
  36. def outer_wrapper(fn):
  37. def inner_wrapper(request, *args, **kwargs):
  38. initial_url = request.full_url if isinstance(request, Request) else request
  39. url = _get_redirect_url(initial_url, max_hops=max_hops)
  40. if url == initial_url:
  41. return fn(request, *args, **kwargs)
  42. warnings.warn(f"The URL {initial_url} ultimately redirects to {url}.")
  43. if not isinstance(request, Request):
  44. return fn(url, *args, **kwargs)
  45. request_attrs = {
  46. attr: getattr(request, attr) for attr in ("data", "headers", "origin_req_host", "unverifiable")
  47. }
  48. # the 'method' attribute does only exist if the request was created with it
  49. if hasattr(request, "method"):
  50. request_attrs["method"] = request.method
  51. return fn(Request(url, **request_attrs), *args, **kwargs)
  52. return inner_wrapper
  53. return outer_wrapper
  54. urlopen = resolve_redirects()(urlopen)
  55. @contextlib.contextmanager
  56. def log_download_attempts(
  57. urls,
  58. *,
  59. dataset_module,
  60. ):
  61. def maybe_add_mock(*, module, name, stack, lst=None):
  62. patcher = unittest.mock.patch(f"torchvision.datasets.{module}.{name}")
  63. try:
  64. mock = stack.enter_context(patcher)
  65. except AttributeError:
  66. return
  67. if lst is not None:
  68. lst.append(mock)
  69. with contextlib.ExitStack() as stack:
  70. download_url_mocks = []
  71. download_file_from_google_drive_mocks = []
  72. for module in [dataset_module, "utils"]:
  73. maybe_add_mock(module=module, name="download_url", stack=stack, lst=download_url_mocks)
  74. maybe_add_mock(
  75. module=module,
  76. name="download_file_from_google_drive",
  77. stack=stack,
  78. lst=download_file_from_google_drive_mocks,
  79. )
  80. maybe_add_mock(module=module, name="extract_archive", stack=stack)
  81. try:
  82. yield
  83. finally:
  84. for download_url_mock in download_url_mocks:
  85. for args, kwargs in download_url_mock.call_args_list:
  86. urls.append(args[0] if args else kwargs["url"])
  87. for download_file_from_google_drive_mock in download_file_from_google_drive_mocks:
  88. for args, kwargs in download_file_from_google_drive_mock.call_args_list:
  89. file_id = args[0] if args else kwargs["file_id"]
  90. urls.append(f"https://drive.google.com/file/d/{file_id}")
  91. def retry(fn, times=1, wait=5.0):
  92. tbs = []
  93. for _ in range(times + 1):
  94. try:
  95. return fn()
  96. except AssertionError as error:
  97. tbs.append("".join(traceback.format_exception(type(error), error, error.__traceback__)))
  98. time.sleep(wait)
  99. else:
  100. raise AssertionError(
  101. "\n".join(
  102. (
  103. "\n",
  104. *[f"{'_' * 40} {idx:2d} {'_' * 40}\n\n{tb}" for idx, tb in enumerate(tbs, 1)],
  105. (
  106. f"Assertion failed {times + 1} times with {wait:.1f} seconds intermediate wait time. "
  107. f"You can find the the full tracebacks above."
  108. ),
  109. )
  110. )
  111. )
  112. @contextlib.contextmanager
  113. def assert_server_response_ok():
  114. try:
  115. yield
  116. except HTTPError as error:
  117. raise AssertionError(f"The server returned {error.code}: {error.reason}.") from error
  118. except URLError as error:
  119. raise AssertionError(
  120. "Connection not possible due to SSL." if "SSL" in str(error) else "The request timed out."
  121. ) from error
  122. except RecursionError as error:
  123. raise AssertionError(str(error)) from error
  124. def assert_url_is_accessible(url, timeout=5.0):
  125. request = Request(url, headers={"User-Agent": USER_AGENT}, method="HEAD")
  126. with assert_server_response_ok():
  127. urlopen(request, timeout=timeout)
  128. def collect_urls(dataset_cls, *args, **kwargs):
  129. urls = []
  130. with contextlib.suppress(Exception), log_download_attempts(
  131. urls, dataset_module=dataset_cls.__module__.split(".")[-1]
  132. ):
  133. dataset_cls(*args, **kwargs)
  134. return [(url, f"{dataset_cls.__name__}, {url}") for url in urls]
  135. # This is a workaround since fixtures, such as the built-in tmp_dir, can only be used within a test but not within a
  136. # parametrization. Thus, we use a single root directory for all datasets and remove it when all download tests are run.
  137. ROOT = tempfile.mkdtemp()
  138. @pytest.fixture(scope="module", autouse=True)
  139. def root():
  140. yield ROOT
  141. dir_util.remove_tree(ROOT)
  142. def places365():
  143. return itertools.chain.from_iterable(
  144. [
  145. collect_urls(
  146. datasets.Places365,
  147. ROOT,
  148. split=split,
  149. small=small,
  150. download=True,
  151. )
  152. for split, small in itertools.product(("train-standard", "train-challenge", "val"), (False, True))
  153. ]
  154. )
  155. def caltech101():
  156. return collect_urls(datasets.Caltech101, ROOT, download=True)
  157. def caltech256():
  158. return collect_urls(datasets.Caltech256, ROOT, download=True)
  159. def cifar10():
  160. return collect_urls(datasets.CIFAR10, ROOT, download=True)
  161. def cifar100():
  162. return collect_urls(datasets.CIFAR100, ROOT, download=True)
  163. def voc():
  164. # TODO: Also test the "2007-test" key
  165. return itertools.chain.from_iterable(
  166. [
  167. collect_urls(datasets.VOCSegmentation, ROOT, year=year, download=True)
  168. for year in ("2007", "2008", "2009", "2010", "2011", "2012")
  169. ]
  170. )
  171. def mnist():
  172. with unittest.mock.patch.object(datasets.MNIST, "mirrors", datasets.MNIST.mirrors[-1:]):
  173. return collect_urls(datasets.MNIST, ROOT, download=True)
  174. def fashion_mnist():
  175. return collect_urls(datasets.FashionMNIST, ROOT, download=True)
  176. def kmnist():
  177. return collect_urls(datasets.KMNIST, ROOT, download=True)
  178. def emnist():
  179. # the 'split' argument can be any valid one, since everything is downloaded anyway
  180. return collect_urls(datasets.EMNIST, ROOT, split="byclass", download=True)
  181. def qmnist():
  182. return itertools.chain.from_iterable(
  183. [collect_urls(datasets.QMNIST, ROOT, what=what, download=True) for what in ("train", "test", "nist")]
  184. )
  185. def moving_mnist():
  186. return collect_urls(datasets.MovingMNIST, ROOT, download=True)
  187. def omniglot():
  188. return itertools.chain.from_iterable(
  189. [collect_urls(datasets.Omniglot, ROOT, background=background, download=True) for background in (True, False)]
  190. )
  191. def phototour():
  192. return itertools.chain.from_iterable(
  193. [
  194. collect_urls(datasets.PhotoTour, ROOT, name=name, download=True)
  195. # The names postfixed with '_harris' point to the domain 'matthewalunbrown.com'. For some reason all
  196. # requests timeout from within CI. They are disabled until this is resolved.
  197. for name in ("notredame", "yosemite", "liberty") # "notredame_harris", "yosemite_harris", "liberty_harris"
  198. ]
  199. )
  200. def sbdataset():
  201. return collect_urls(datasets.SBDataset, ROOT, download=True)
  202. def sbu():
  203. return collect_urls(datasets.SBU, ROOT, download=True)
  204. def semeion():
  205. return collect_urls(datasets.SEMEION, ROOT, download=True)
  206. def stl10():
  207. return collect_urls(datasets.STL10, ROOT, download=True)
  208. def svhn():
  209. return itertools.chain.from_iterable(
  210. [collect_urls(datasets.SVHN, ROOT, split=split, download=True) for split in ("train", "test", "extra")]
  211. )
  212. def usps():
  213. return itertools.chain.from_iterable(
  214. [collect_urls(datasets.USPS, ROOT, train=train, download=True) for train in (True, False)]
  215. )
  216. def celeba():
  217. return collect_urls(datasets.CelebA, ROOT, download=True)
  218. def widerface():
  219. return collect_urls(datasets.WIDERFace, ROOT, download=True)
  220. def kinetics():
  221. return itertools.chain.from_iterable(
  222. [
  223. collect_urls(
  224. datasets.Kinetics,
  225. path.join(ROOT, f"Kinetics{num_classes}"),
  226. frames_per_clip=1,
  227. num_classes=num_classes,
  228. split=split,
  229. download=True,
  230. )
  231. for num_classes, split in itertools.product(("400", "600", "700"), ("train", "val"))
  232. ]
  233. )
  234. def kitti():
  235. return itertools.chain.from_iterable(
  236. [collect_urls(datasets.Kitti, ROOT, train=train, download=True) for train in (True, False)]
  237. )
  238. def stanford_cars():
  239. return itertools.chain.from_iterable(
  240. [collect_urls(datasets.StanfordCars, ROOT, split=split, download=True) for split in ["train", "test"]]
  241. )
  242. def url_parametrization(*dataset_urls_and_ids_fns):
  243. return pytest.mark.parametrize(
  244. "url",
  245. [
  246. pytest.param(url, id=id)
  247. for dataset_urls_and_ids_fn in dataset_urls_and_ids_fns
  248. for url, id in sorted(set(dataset_urls_and_ids_fn()))
  249. ],
  250. )
  251. @url_parametrization(
  252. caltech101,
  253. caltech256,
  254. cifar10,
  255. cifar100,
  256. # The VOC download server is unstable. See https://github.com/pytorch/vision/issues/2953 for details.
  257. # voc,
  258. mnist,
  259. fashion_mnist,
  260. kmnist,
  261. emnist,
  262. qmnist,
  263. omniglot,
  264. phototour,
  265. sbdataset,
  266. semeion,
  267. stl10,
  268. svhn,
  269. usps,
  270. celeba,
  271. widerface,
  272. kinetics,
  273. kitti,
  274. places365,
  275. sbu,
  276. )
  277. def test_url_is_accessible(url):
  278. """
  279. If you see this test failing, find the offending dataset in the parametrization and move it to
  280. ``test_url_is_not_accessible`` and link an issue detailing the problem.
  281. """
  282. retry(lambda: assert_url_is_accessible(url))
  283. @url_parametrization(
  284. stanford_cars, # https://github.com/pytorch/vision/issues/7545
  285. )
  286. @pytest.mark.xfail
  287. def test_url_is_not_accessible(url):
  288. """
  289. As the name implies, this test is the 'inverse' of ``test_url_is_accessible``. Since the download servers are
  290. beyond our control, some files might not be accessible for longer stretches of time. Still, we want to know if they
  291. come back up, or if we need to remove the download functionality of the dataset for good.
  292. If you see this test failing, find the offending dataset in the parametrization and move it to
  293. ``test_url_is_accessible``.
  294. """
  295. retry(lambda: assert_url_is_accessible(url))