35550e0a568d43d90b84ca46bb4dfa42823846f4
[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         if os.path.exists('../../mkfs.btrfs'):
41             mkfs = '../../mkfs.btrfs'
42         else:
43             mkfs = 'mkfs.btrfs'
44         try:
45             subprocess.check_call([mkfs, '-q', self.image])
46             subprocess.check_call(['mount', '-o', 'loop', '--', self.image, self.mountpoint])
47         except Exception as e:
48             os.remove(self.image)
49             os.rmdir(self.mountpoint)
50             raise e
51
52     def tearDown(self):
53         try:
54             subprocess.check_call(['umount', self.mountpoint])
55         finally:
56             os.remove(self.image)
57             os.rmdir(self.mountpoint)
58
59     @staticmethod
60     def path_or_fd(path, open_flags=os.O_RDONLY):
61         yield path
62         yield path.encode()
63         if HAVE_PATH_LIKE:
64             yield PurePath(path)
65         fd = os.open(path, open_flags)
66         try:
67             yield fd
68         finally:
69             os.close(fd)
70