Don't install docker in arvbox now that arvados-server install does it.
[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         c = collection.Collection()
53         for path, data in listitems(contents):
54             with c.open(path, 'wb') as f:
55                 f.write(data)
56         c.save_new()
57
58         return (c.manifest_locator(),
59                 c.portable_data_hash(),
60                 c.manifest_text(strip=strip_manifest))
61
62     def run_get(self, args):
63         self.stdout.seek(0, 0)
64         self.stdout.truncate(0)
65         self.stderr.seek(0, 0)
66         self.stderr.truncate(0)
67         return arv_get.main(args, self.stdout, self.stderr)
68
69     def test_version_argument(self):
70         with tutil.redirected_streams(
71                 stdout=tutil.StringIO, stderr=tutil.StringIO) as (out, err):
72             with self.assertRaises(SystemExit):
73                 self.run_get(['--version'])
74         self.assertVersionOutput(out, err)
75
76     def test_get_single_file(self):
77         # Get the file using the collection's locator
78         r = self.run_get(["{}/subdir/baz.txt".format(self.col_loc), '-'])
79         self.assertEqual(0, r)
80         self.assertEqual(b'baz', self.stdout.getvalue())
81         # Then, try by PDH
82         r = self.run_get(["{}/subdir/baz.txt".format(self.col_pdh), '-'])
83         self.assertEqual(0, r)
84         self.assertEqual(b'baz', self.stdout.getvalue())
85
86     def test_get_block(self):
87         # Get raw data using a block locator
88         blk = re.search(' (acbd18\S+\+A\S+) ', self.col_manifest).group(1)
89         r = self.run_get([blk, '-'])
90         self.assertEqual(0, r)
91         self.assertEqual(b'foo', self.stdout.getvalue())
92
93     def test_get_multiple_files(self):
94         # Download the entire collection to the temp directory
95         r = self.run_get(["{}/".format(self.col_loc), self.tempdir])
96         self.assertEqual(0, r)
97         with open(os.path.join(self.tempdir, "foo.txt"), "r") as f:
98             self.assertEqual("foo", f.read())
99         with open(os.path.join(self.tempdir, "bar.txt"), "r") as f:
100             self.assertEqual("bar", f.read())
101         with open(os.path.join(self.tempdir, "subdir", "baz.txt"), "r") as f:
102             self.assertEqual("baz", f.read())
103
104     def test_get_collection_unstripped_manifest(self):
105         dummy_token = "+Axxxxxxx"
106         # Get the collection manifest by UUID
107         r = self.run_get([self.col_loc, self.tempdir])
108         self.assertEqual(0, r)
109         m_from_collection = re.sub(r"\+A[0-9a-f@]+", dummy_token, self.col_manifest)
110         with open(os.path.join(self.tempdir, self.col_loc), "r") as f:
111             # Replace manifest tokens before comparison to avoid races
112             m_from_file = re.sub(r"\+A[0-9a-f@]+", dummy_token, f.read())
113             self.assertEqual(m_from_collection, m_from_file)
114         # Get the collection manifest by PDH
115         r = self.run_get([self.col_pdh, self.tempdir])
116         self.assertEqual(0, r)
117         with open(os.path.join(self.tempdir, self.col_pdh), "r") as f:
118             # Replace manifest tokens before comparison to avoid races
119             m_from_file = re.sub(r"\+A[0-9a-f@]+", dummy_token, f.read())
120             self.assertEqual(m_from_collection, m_from_file)
121
122     def test_get_collection_stripped_manifest(self):
123         col_loc, col_pdh, col_manifest = self.write_test_collection(
124             strip_manifest=True)
125         # Get the collection manifest by UUID
126         r = self.run_get(['--strip-manifest', col_loc, self.tempdir])
127         self.assertEqual(0, r)
128         with open(os.path.join(self.tempdir, col_loc), "r") as f:
129             self.assertEqual(col_manifest, f.read())
130         # Get the collection manifest by PDH
131         r = self.run_get(['--strip-manifest', col_pdh, self.tempdir])
132         self.assertEqual(0, r)
133         with open(os.path.join(self.tempdir, col_pdh), "r") as f:
134             self.assertEqual(col_manifest, f.read())
135
136     def test_invalid_collection(self):
137         # Asking for an invalid collection should generate an error.
138         r = self.run_get(['this-uuid-seems-to-be-fake', self.tempdir])
139         self.assertNotEqual(0, r)
140
141     def test_invalid_file_request(self):
142         # Asking for an inexistant file within a collection should generate an error.
143         r = self.run_get(["{}/im-not-here.txt".format(self.col_loc), self.tempdir])
144         self.assertNotEqual(0, r)
145
146     def test_invalid_destination(self):
147         # Asking to place the collection's files on a non existant directory
148         # should generate an error.
149         r = self.run_get([self.col_loc, "/fake/subdir/"])
150         self.assertNotEqual(0, r)
151
152     def test_preexistent_destination(self):
153         # Asking to place a file with the same path as a local one should
154         # generate an error and avoid overwrites.
155         with open(os.path.join(self.tempdir, "foo.txt"), "w") as f:
156             f.write("another foo")
157         r = self.run_get(["{}/foo.txt".format(self.col_loc), self.tempdir])
158         self.assertNotEqual(0, r)
159         with open(os.path.join(self.tempdir, "foo.txt"), "r") as f:
160             self.assertEqual("another foo", f.read())
161
162     def test_no_progress_when_stderr_not_a_tty(self):
163         # Create a collection with a big file (>64MB) to force the progress
164         # to be printed
165         c = collection.Collection()
166         with c.open('bigfile.txt', 'wb') as f:
167             for _ in range(65):
168                 f.write("x" * 1024 * 1024)
169         c.save_new()
170         tmpdir = self.make_tmpdir()
171         # Simulate a TTY stderr
172         stderr = mock.MagicMock()
173         stdout = tutil.BytesIO()
174
175         # Confirm that progress is written to stderr when is a tty
176         stderr.isatty.return_value = True
177         r = arv_get.main(['{}/bigfile.txt'.format(c.manifest_locator()),
178                           '{}/bigfile.txt'.format(tmpdir)],
179                          stdout, stderr)
180         self.assertEqual(0, r)
181         self.assertEqual(b'', stdout.getvalue())
182         self.assertTrue(stderr.write.called)
183
184         # Clean up and reset stderr mock
185         os.remove('{}/bigfile.txt'.format(tmpdir))
186         stderr = mock.MagicMock()
187         stdout = tutil.BytesIO()
188
189         # Confirm that progress is not written to stderr when isn't a tty
190         stderr.isatty.return_value = False
191         r = arv_get.main(['{}/bigfile.txt'.format(c.manifest_locator()),
192                           '{}/bigfile.txt'.format(tmpdir)],
193                          stdout, stderr)
194         self.assertEqual(0, r)
195         self.assertEqual(b'', stdout.getvalue())
196         self.assertFalse(stderr.write.called)
197
198     request_id_regex = r'INFO: X-Request-Id: req-[a-z0-9]{20}\n'
199
200     def test_request_id_logging_on(self):
201         r = self.run_get(["-v", "{}/".format(self.col_loc), self.tempdir])
202         self.assertEqual(0, r)
203         self.assertRegex(self.stderr.getvalue(), self.request_id_regex)
204
205     def test_request_id_logging_off(self):
206         r = self.run_get(["{}/".format(self.col_loc), self.tempdir])
207         self.assertEqual(0, r)
208         self.assertNotRegex(self.stderr.getvalue(), self.request_id_regex)