d2c6ff282b786ee56d3a33efded40bd7962bd587
[platform/upstream/btrfs-progs.git] / libbtrfsutil / python / tests / __init__.py
1 # Copyright (C) 2018 Facebook
2 #
3 # This file is part of libbtrfsutil.
4 #
5 # libbtrfsutil is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # libbtrfsutil is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with libbtrfsutil.  If not, see <http://www.gnu.org/licenses/>.
17
18 import os
19 from pathlib import PurePath
20 import subprocess
21 import tempfile
22 import unittest
23
24
25 HAVE_PATH_LIKE = hasattr(PurePath, '__fspath__')
26
27
28 @unittest.skipIf(os.geteuid() != 0, 'must be run as root')
29 class BtrfsTestCase(unittest.TestCase):
30     def setUp(self):
31         self.mountpoint = tempfile.mkdtemp()
32         try:
33             with tempfile.NamedTemporaryFile(delete=False) as f:
34                 os.truncate(f.fileno(), 1024 * 1024 * 1024)
35                 self.image = f.name
36         except Exception as e:
37             os.rmdir(self.mountpoint)
38             raise e
39
40         try:
41             subprocess.check_call(['mkfs.btrfs', '-q', self.image])
42             subprocess.check_call(['mount', '-o', 'loop', '--', self.image, self.mountpoint])
43         except Exception as e:
44             os.remove(self.image)
45             os.rmdir(self.mountpoint)
46             raise e
47
48     def tearDown(self):
49         try:
50             subprocess.check_call(['umount', self.mountpoint])
51         finally:
52             os.remove(self.image)
53             os.rmdir(self.mountpoint)
54
55     @staticmethod
56     def path_or_fd(path, open_flags=os.O_RDONLY):
57         yield path
58         yield path.encode()
59         if HAVE_PATH_LIKE:
60             yield PurePath(path)
61         fd = os.open(path, open_flags)
62         try:
63             yield fd
64         finally:
65             os.close(fd)
66