File: test_backend_instance.py

package info (click to toggle)
duplicity 3.0.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,492 kB
  • sloc: python: 25,523; sh: 976; ansic: 392; makefile: 83
file content (290 lines) | stat: -rw-r--r-- 11,178 bytes parent folder | download
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
288
289
290
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4; encoding:utf-8 -*-
#
# Copyright 2014 Canonical Ltd
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA


import io
import os
import subprocess
import unittest
import logging

import pytest

import duplicity.backend
from duplicity import log
from duplicity import path
from duplicity import util
from duplicity.errors import BackendException
from testing import _runtest_dir
from . import UnitTestCase


class BackendInstanceBase(UnitTestCase):
    def setUp(self):
        super().setUp()
        assert not os.system(f"rm -rf {_runtest_dir}/testfiles")
        os.makedirs(f"{_runtest_dir}/testfiles")
        self.backend = None
        self.local = path.Path(f"{_runtest_dir}/testfiles/local")
        self.local.writefileobj(io.BytesIO(7 * b"hello"))

    def tearDown(self):
        assert not os.system(f"rm -rf {_runtest_dir}/testfiles")
        if self.backend is None:
            return
        if hasattr(self.backend, "_close"):
            self.backend._close()
        super().tearDown()

    def test_get(self):
        if self.backend is None:
            return
        self.backend._put(self.local, b"file-a")
        getfile = path.Path(f"{_runtest_dir}/testfiles/getfile")
        self.backend._get(b"file-a", getfile)
        self.assertTrue(self.local.compare_data(getfile))

    def test_list(self):
        if self.backend is None:
            return
        self.backend._put(self.local, b"file-a")
        self.backend._put(self.local, b"file-b")
        # It's OK for backends to create files as a side effect of put (e.g.
        # the par2 backend does), so only check that at least a and b exist.
        self.assertTrue(b"file-a" in self.backend._list())
        self.assertTrue(b"file-b" in self.backend._list())

    def test_delete(self):
        if self.backend is None:
            return
        if not hasattr(self.backend, "_delete"):
            self.assertTrue(hasattr(self.backend, "_delete_list"))
            return
        self.backend._put(self.local, b"file-a")
        self.backend._put(self.local, b"file-b")
        self.backend._delete(b"file-a")
        self.assertFalse(b"file-a" in self.backend._list())
        self.assertTrue(b"file-b" in self.backend._list())

    def test_delete_clean(self):
        if self.backend is None:
            return
        if not hasattr(self.backend, "_delete"):
            self.assertTrue(hasattr(self.backend, "_delete_list"))
            return
        self.backend._put(self.local, b"file-a")
        self.backend._delete(b"file-a")
        self.assertFalse(b"file-a" in self.backend._list())

    def test_delete_missing(self):
        if self.backend is None:
            return
        if not hasattr(self.backend, "_delete"):
            self.assertTrue(hasattr(self.backend, "_delete_list"))
            return
        # Backends can either silently ignore this, or throw an error
        # that gives log.ErrorCode.backend_not_found.
        try:
            self.backend._delete(b"file-a")
        except BackendException as e:
            pass  # Something went wrong, but it was an 'expected' something
        except Exception as e:
            code = duplicity.backend._get_code_from_exception(self.backend, "delete", e)
            self.assertEqual(code, log.ErrorCode.backend_not_found)

    def test_delete_list(self):
        if self.backend is None:
            return
        if not hasattr(self.backend, "_delete_list"):
            self.assertTrue(hasattr(self.backend, "_delete"))
            return
        self.backend._put(self.local, b"file-a")
        self.backend._put(self.local, b"file-b")
        self.backend._put(self.local, b"file-c")
        self.backend._delete_list([b"file-a", b"d", b"file-c"])
        files = self.backend._list()
        self.assertFalse(b"file-a" in files, files)
        self.assertTrue(b"file-b" in files, files)
        self.assertFalse(b"file-c" in files, files)

    def test_move(self):
        if self.backend is None:
            return
        if not hasattr(self.backend, "_move"):
            return

        copy = path.Path(f"{_runtest_dir}/testfiles/copy")
        self.local.copy(copy)

        self.backend._move(self.local, b"file-a")
        self.assertTrue(b"file-a" in self.backend._list())
        self.assertFalse(self.local.exists())

        getfile = path.Path(f"{_runtest_dir}/testfiles/getfile")
        self.backend._get(b"file-a", getfile)
        self.assertTrue(copy.compare_data(getfile))

    def test_query_exists(self):
        if self.backend is None:
            return
        if not hasattr(self.backend, "_query"):
            return
        self.backend._put(self.local, b"file-a")
        info = self.backend._query(b"file-a")
        self.assertEqual(info["size"], self.local.getsize())

    def test_query_missing(self):
        if self.backend is None:
            return
        if not hasattr(self.backend, "_query"):
            return
        # Backends can either return -1 themselves, or throw an error
        # that gives log.ErrorCode.backend_not_found.
        try:
            info = self.backend._query(b"missing-file")
        except BackendException as e:  # pylint:
            pass  # Something went wrong, but it was an 'expected' something
        except Exception as e:
            code = duplicity.backend._get_code_from_exception(self.backend, "query", e)
            self.assertEqual(code, log.ErrorCode.backend_not_found)
        else:
            self.assertEqual(info["size"], -1)

    def test_query_list(self):
        if self.backend is None:
            return
        if not hasattr(self.backend, "_query_list"):
            return
        self.backend._put(self.local, b"file-a")
        self.backend._put(self.local, b"file-c")
        info = self.backend._query_list([b"file-a", b"file-b"])
        self.assertEqual(info[b"file-a"]["size"], self.local.getsize())
        self.assertEqual(info[b"file-b"]["size"], -1)
        self.assertFalse(b"file-c" in info)


class LocalBackendTest(BackendInstanceBase):
    def setUp(self):
        super().setUp()
        url = f"file://{_runtest_dir}/testfiles/output"
        self.backend = duplicity.backend.get_backend_object(url)
        self.assertEqual(self.backend.__class__.__name__, "LocalBackend")


# TODO: Add par2-specific tests here, to confirm that we can recover
@unittest.skipIf(not util.which("par2"), "par2 not installed")
class Par2BackendTest(BackendInstanceBase):
    def setUp(self):
        super().setUp()
        url = f"par2+file://{_runtest_dir}/testfiles/output"
        self.backend = duplicity.backend.get_backend_object(url)
        self.assertEqual(self.backend.__class__.__name__, "Par2Backend")


# TODO: Fix so localhost is not required.  Fails on LP and GitLab
# class RsyncBackendTest(BackendInstanceBase):
#     def setUp(self):
#         super().setUp()
#         os.makedirs('{0}/testfiles/output')  # rsync needs it to exist first
#         url = 'rsync://localhost:2222//%s/{0}/testfiles/output' % os.getcwd()
#         self.backend = duplicity.backend.get_backend_object(url)
#         self.assertEqual(self.backend.__class__.__name__, 'RsyncBackend')


class TahoeBackendTest(BackendInstanceBase):
    def setUp(self):
        super().setUp()
        os.makedirs(f"{_runtest_dir}/testfiles/output")
        url = f"tahoe://{_runtest_dir}/testfiles/output"
        self.backend = duplicity.backend.get_backend_object(url)
        self.assertEqual(self.backend.__class__.__name__, "TAHOEBackend")


# TODO: Modernize hsi backend stub
# class HSIBackendTest(BackendInstanceBase):
#     def setUp(self):
#         super().setUp()
#         os.makedirs('{0}/testfiles/output')
#         # hostname is ignored...  Seemingly on purpose
#         url = 'hsi://hostname%s/{0}/testfiles/output' % os.getcwd()
#         self.backend = duplicity.backend.get_backend_object(url)
#         self.assertEqual(self.backend.__class__.__name__, 'HSIBackend')


@unittest.skipIf(not util.which("lftp"), "lftp not installed")
class FTPBackendTest(BackendInstanceBase):
    def setUp(self):
        super().setUp()
        os.makedirs(f"{_runtest_dir}/testfiles/output")
        url = f"ftp://user:pass@hostname/{_runtest_dir}/testfiles/output"
        self.backend = duplicity.backend.get_backend_object(url)
        self.assertEqual(self.backend.__class__.__name__, "LFTPBackend")


@unittest.skipIf(not util.which("lftp"), "lftp not installed")
class FTPSBackendTest(BackendInstanceBase):
    def setUp(self):
        super().setUp()
        os.makedirs(f"{_runtest_dir}/testfiles/output")
        url = f"ftps://user:pass@hostname/{_runtest_dir}/testfiles/output"
        self.backend = duplicity.backend.get_backend_object(url)
        self.assertEqual(self.backend.__class__.__name__, "LFTPBackend")


@unittest.skipIf(not util.which("rclone"), "rclone not installed")
class RCloneBackendTest(BackendInstanceBase):
    def setUp(self):
        super().setUp()
        # add a duptest local config
        try:
            assert not os.system("rclone config create duptest local config_is_local true")
            self.delete_config = True
        except Exception as e:
            self.delete_config = False
        os.makedirs(f"{_runtest_dir}/testfiles/output")
        url = f"rclone://duptest:/{_runtest_dir}/testfiles/output"
        self.backend = duplicity.backend.get_backend_object(url)
        self.assertEqual(self.backend.__class__.__name__, "RcloneBackend")

    def tearDown(self):
        if self.delete_config:
            assert not os.system("rclone config delete duptest")
        super().tearDown()


# TODO: Need fix to work on both Gitlab Docker and personal Docker.
# def in_docker():
#     return os.path.exists("/.dockerenv")
#
#
# TODO: Find out why ssh does not work in Docker.
# @unittest.skipIf(not in_docker(), "Requires Docker / duplicity_test")
# class SFTPBackendTest(BackendInstanceBase):
#     def setUp(self):
#         super().setUp()
#         url = f"pexpect+sftp://testuser:testuser@ssh_server/testdup"
#         self.backend = duplicity.backend.get_backend_object(url)
#         self.assertEqual(self.backend.__class__.__name__, "SSHPxpectBackend")
#         for fn in b"file-a", b"file-b", b"file-c":
#             try:
#                 self.backend._delete(fn)
#             except Exception as e:
#                 log.Error(f"An exception occurred while deleting file {fn}: {e}")
#                 pass