xref: /freebsd/tests/atf_python/utils.py (revision d8e36cd2b10f78470c1de56337f685c10ce26ed2)
1#!/usr/bin/env python3
2import os
3import pwd
4from ctypes import CDLL
5from ctypes import get_errno
6from ctypes.util import find_library
7from typing import Dict
8from typing import List
9from typing import Optional
10
11import pytest
12
13
14def nodeid_to_method_name(nodeid: str) -> str:
15    """file_name.py::ClassName::method_name[parametrize] -> method_name"""
16    return nodeid.split("::")[-1].split("[")[0]
17
18
19class LibCWrapper(object):
20    def __init__(self):
21        path: Optional[str] = find_library("c")
22        if path is None:
23            raise RuntimeError("libc not found")
24        self._libc = CDLL(path, use_errno=True)
25
26    def modfind(self, mod_name: str) -> int:
27        if self._libc.modfind(bytes(mod_name, encoding="ascii")) == -1:
28            return get_errno()
29        return 0
30
31    def jail_attach(self, jid: int) -> int:
32        if self._libc.jail_attach(jid) != 0:
33            return get_errno()
34        return 0
35
36
37libc = LibCWrapper()
38
39
40class BaseTest(object):
41    NEED_ROOT: bool = False  # True if the class needs root privileges for the setup
42    TARGET_USER = None  # Set to the target user by the framework
43    REQUIRED_MODULES: List[str] = []
44
45    def _check_modules(self):
46        for mod_name in self.REQUIRED_MODULES:
47            error_code = libc.modfind(mod_name)
48            if error_code != 0:
49                err_str = os.strerror(error_code)
50                pytest.skip(
51                    "kernel module '{}' not available: {}".format(mod_name, err_str)
52                )
53    @property
54    def atf_vars(self) -> Dict[str, str]:
55        px = "_ATF_VAR_"
56        return {k[len(px):]: v for k, v in os.environ.items() if k.startswith(px)}
57
58    def drop_privileges_user(self, user: str):
59        uid = pwd.getpwnam(user)[2]
60        print("Dropping privs to {}/{}".format(user, uid))
61        os.setuid(uid)
62
63    def drop_privileges(self):
64        if self.TARGET_USER:
65            if self.TARGET_USER == "unprivileged":
66                user = self.atf_vars["unprivileged-user"]
67            else:
68                user = self.TARGET_USER
69            self.drop_privileges_user(user)
70
71    @property
72    def test_id(self) -> str:
73        # 'test_ip6_output.py::TestIP6Output::test_output6_pktinfo[ipandif] (setup)'
74        return os.environ.get("PYTEST_CURRENT_TEST").split(" ")[0]
75
76    def setup_method(self, method):
77        """Run all pre-requisits for the test execution"""
78        self._check_modules()
79