17004: Fix lingering resource error
[arvados.git] / sdk / python / tests / test_arv_get.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 from __future__ import absolute_import
6 from future.utils import listitems
7 import io
8 import logging
9 import mock
10 import os
11 import re
12 import shutil
13 import tempfile
14
15 import arvados
16 import arvados.collection as collection
17 import arvados.commands.get as arv_get
18 from . import run_test_server
19
20 from . import arvados_testutil as tutil
21 from .arvados_testutil import ArvadosBaseTestCase
22
23 class ArvadosGetTestCase(run_test_server.TestCaseWithServers,
24                          tutil.VersionChecker,
25                          ArvadosBaseTestCase):
26     MAIN_SERVER = {}
27     KEEP_SERVER = {}
28
29     def setUp(self):
30         super(ArvadosGetTestCase, self).setUp()
31         self.tempdir = tempfile.mkdtemp()
32         self.col_loc, self.col_pdh, self.col_manifest = self.write_test_collection()
33
34         self.stdout = tutil.BytesIO()
35         self.stderr = tutil.StringIO()
36         self.loggingHandler = logging.StreamHandler(self.stderr)
37         self.loggingHandler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
38         logging.getLogger().addHandler(self.loggingHandler)
39
40     def tearDown(self):
41         logging.getLogger().removeHandler(self.loggingHandler)
42         super(ArvadosGetTestCase, self).tearDown()
43         shutil.rmtree(self.tempdir)
44
45     def write_test_collection(self,
46                               strip_manifest=False,
47                               contents = {
48                                   'foo.txt' : 'foo',
49                                   'bar.txt' : 'bar',
50                                   'subdir/baz.txt' : 'baz',
51                               }):
52         api = arvados.api()
53         c = collection.Collection(api_client=api)
54         for path, data in listitems(contents):
55             with c.open(path, 'wb') as f:
56                 f.write(data)
57         c.save_new()
58
59         api.close_connections()
60
61         return (c.manifest_locator(),
62                 c.portable_data_hash(),
63                 c.manifest_text(strip=strip_manifest))
64
65     def run_get(self, args):
66         self.stdout.seek(0, 0)
67         self.stdout.truncate(0)
68         self.stderr.seek(0, 0)
69         self.stderr.truncate(0)
70         return arv_get.main(args, self.stdout, self.stderr)
71
72     def test_version_argument(self):
73         with tutil.redirected_streams(
74                 stdout=tutil.StringIO, stderr=tutil.StringIO) as (out, err):
75             with self.assertRaises(SystemExit):
76                 self.run_get(['--version'])
77         self.assertVersionOutput(out, err)
78
79     def test_get_single_file(self):
80         # Get the file using the collection's locator
81         r = self.run_get(["{}/subdir/baz.txt".format(self.col_loc), '-'])
82         self.assertEqual(0, r)
83         self.assertEqual(b'baz', self.stdout.getvalue())
84         # Then, try by PDH
85         r = self.run_get(["{}/subdir/baz.txt".format(self.col_pdh), '-'])
86         self.assertEqual(0, r)
87         self.assertEqual(b'baz', self.stdout.getvalue())
88
89     def test_get_block(self):
90         # Get raw data using a block locator
91         blk = re.search(' (acbd18\S+\+A\S+) ', self.col_manifest).group(1)
92         r = self.run_get([blk, '-'])
93         self.assertEqual(0, r)
94         self.assertEqual(b'foo', self.stdout.getvalue())
95
96     def test_get_multiple_files(self):
97         # Download the entire collection to the temp directory
98         r = self.run_get(["{}/".format(self.col_loc), self.tempdir])
99         self.assertEqual(0, r)
100         with open(os.path.join(self.tempdir, "foo.txt"), "r") as f:
101             self.assertEqual("foo", f.read())
102         with open(os.path.join(self.tempdir, "bar.txt"), "r") as f:
103             self.assertEqual("bar", f.read())
104         with open(os.path.join(self.tempdir, "subdir", "baz.txt"), "r") as f:
105             self.assertEqual("baz", f.read())
106
107     def test_get_collection_unstripped_manifest(self):
108         dummy_token = "+Axxxxxxx"
109         # Get the collection manifest by UUID
110         r = self.run_get([self.col_loc, self.tempdir])
111         self.assertEqual(0, r)
112         m_from_collection = re.sub(r"\+A[0-9a-f@]+", dummy_token, self.col_manifest)
113         with open(os.path.join(self.tempdir, self.col_loc), "r") as f:
114             # Replace manifest tokens before comparison to avoid races
115             m_from_file = re.sub(r"\+A[0-9a-f@]+", dummy_token, f.read())
116             self.assertEqual(m_from_collection, m_from_file)
117         # Get the collection manifest by PDH
118         r = self.run_get([self.col_pdh, self.tempdir])
119         self.assertEqual(0, r)
120         with open(os.path.join(self.tempdir, self.col_pdh), "r") as f:
121             # Replace manifest tokens before comparison to avoid races
122             m_from_file = re.sub(r"\+A[0-9a-f@]+", dummy_token, f.read())
123             self.assertEqual(m_from_collection, m_from_file)
124
125     def test_get_collection_stripped_manifest(self):
126         col_loc, col_pdh, col_manifest = self.write_test_collection(
127             strip_manifest=True)
128         # Get the collection manifest by UUID
129         r = self.run_get(['--strip-manifest', col_loc, self.tempdir])
130         self.assertEqual(0, r)
131         with open(os.path.join(self.tempdir, col_loc), "r") as f:
132             self.assertEqual(col_manifest, f.read())
133         # Get the collection manifest by PDH
134         r = self.run_get(['--strip-manifest', col_pdh, self.tempdir])
135         self.assertEqual(0, r)
136         with open(os.path.join(self.tempdir, col_pdh), "r") as f:
137             self.assertEqual(col_manifest, f.read())
138
139     def test_invalid_collection(self):
140         # Asking for an invalid collection should generate an error.
141         r = self.run_get(['this-uuid-seems-to-be-fake', self.tempdir])
142         self.assertNotEqual(0, r)
143
144     def test_invalid_file_request(self):
145         # Asking for an inexistant file within a collection should generate an error.
146         r = self.run_get(["{}/im-not-here.txt".format(self.col_loc), self.tempdir])
147         self.assertNotEqual(0, r)
148
149     def test_invalid_destination(self):
150         # Asking to place the collection's files on a non existant directory
151         # should generate an error.
152         r = self.run_get([self.col_loc, "/fake/subdir/"])
153         self.assertNotEqual(0, r)
154
155     def test_preexistent_destination(self):
156         # Asking to place a file with the same path as a local one should
157         # generate an error and avoid overwrites.
158         with open(os.path.join(self.tempdir, "foo.txt"), "w") as f:
159             f.write("another foo")
160         r = self.run_get(["{}/foo.txt".format(self.col_loc), self.tempdir])
161         self.assertNotEqual(0, r)
162         with open(os.path.join(self.tempdir, "foo.txt"), "r") as f:
163             self.assertEqual("another foo", f.read())
164
165     def test_no_progress_when_stderr_not_a_tty(self):
166         # Create a collection with a big file (>64MB) to force the progress
167         # to be printed
168         c = collection.Collection()
169         with c.open('bigfile.txt', 'wb') as f:
170             for _ in range(65):
171                 f.write("x" * 1024 * 1024)
172         c.save_new()
173         tmpdir = self.make_tmpdir()
174         # Simulate a TTY stderr
175         stderr = mock.MagicMock()
176         stdout = tutil.BytesIO()
177
178         # Confirm that progress is written to stderr when is a tty
179         stderr.isatty.return_value = True
180         r = arv_get.main(['{}/bigfile.txt'.format(c.manifest_locator()),
181                           '{}/bigfile.txt'.format(tmpdir)],
182                          stdout, stderr)
183         self.assertEqual(0, r)
184         self.assertEqual(b'', stdout.getvalue())
185         self.assertTrue(stderr.write.called)
186
187         # Clean up and reset stderr mock
188         os.remove('{}/bigfile.txt'.format(tmpdir))
189         stderr = mock.MagicMock()
190         stdout = tutil.BytesIO()
191
192         # Confirm that progress is not written to stderr when isn't a tty
193         stderr.isatty.return_value = False
194         r = arv_get.main(['{}/bigfile.txt'.format(c.manifest_locator()),
195                           '{}/bigfile.txt'.format(tmpdir)],
196                          stdout, stderr)
197         self.assertEqual(0, r)
198         self.assertEqual(b'', stdout.getvalue())
199         self.assertFalse(stderr.write.called)
200
201     request_id_regex = r'INFO: X-Request-Id: req-[a-z0-9]{20}\n'
202
203     def test_request_id_logging_on(self):
204         r = self.run_get(["-v", "{}/".format(self.col_loc), self.tempdir])
205         self.assertEqual(0, r)
206         self.assertRegex(self.stderr.getvalue(), self.request_id_regex)
207
208     def test_request_id_logging_off(self):
209         r = self.run_get(["{}/".format(self.col_loc), self.tempdir])
210         self.assertEqual(0, r)
211         self.assertNotRegex(self.stderr.getvalue(), self.request_id_regex)