HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

test/test-udev.py

86,568 bytesGit mode 100755Download original fileLGPL-2.1-or-later

Git blob: c2ee8b1bc1440cefc7a546c7393d72ec854c7e6d

Lines 1–1000 of 2,471

#!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1-or-later
 
# pylint: disable=redefined-outer-name,no-else-return,multiple-imports
# pylint: disable=consider-using-with,global-statement
 
# udev test
#
# Provides automated testing of the udev binary.
# The whole test is self contained in this file, except the matching sysfs tree.
# Simply extend RULES to add a new test.
#
# Every test is driven by its own temporary config file.
# This program prepares the environment, creates the config and calls udev.
#
# udev parses the rules, looks at the provided sysfs and first creates and then
# removes the device node. After creation and removal the result is checked
# against the expected value and the result is printed.
 
import dataclasses
import functools
import grp
import os
import pwd
import re
import stat
import subprocess
import sys
import tempfile
import textwrap
from pathlib import Path
from typing import Callable, Optional
 
try:
    import pytest
except ImportError as e:
    print(str(e), file=sys.stderr)
    sys.exit(77)
 
 
SYS_SCRIPT = Path(__file__).with_name('sys-script.py')
try:
    UDEV_BIN = Path(os.environ['UDEV_RULE_RUNNER'])
except KeyError:
    UDEV_BIN = Path(__file__).parent / 'manual/test-udev-rule-runner'
UDEV_BIN = UDEV_BIN.absolute()
 
# Those will be set by the udev_setup() fixture
UDEV_RUN = UDEV_RULES = UDEV_DEV = UDEV_SYS = None
 
# Relax sd-device's sysfs verification, since we want to provide a fake sysfs
# here that actually is a tmpfs.
os.environ['SYSTEMD_DEVICE_VERIFY_SYSFS'] = '0'
 
rules_10k_tags = \
    '\n'.join(f'KERNEL=="sda", TAG+="test{i + 1}"'
              for i in range(10_000))  # fmt: skip
 
rules_10k_tags_continuation = \
    ',\\\n'.join(('KERNEL=="sda"',
                  *(f'TAG+="test{i + 1}"' for i in range(10_000))))  # fmt: skip
 
 
@dataclasses.dataclass
class Device:
    devpath: str
    devnode: Optional[str] = None
    exp_links: Optional[list[str]] = None
    not_exp_links: Optional[list[str]] = None
 
    exp_perms: Optional[int] = None
    exp_major_minor: Optional[str] = None
 
    def check_permissions(self, st: os.stat_result) -> None:
        if self.exp_perms is None:
            return
 
        user, group, mode = self.exp_perms.split(':')
 
        if user:
            try:
                uid = pwd.getpwnam(user).pw_uid
            except KeyError:
                uid = int(user)
            assert uid == st.st_uid
 
        if group:
            try:
                gid = grp.getgrnam(group).gr_gid
            except KeyError:
                gid = int(group)
            assert gid == st.st_gid
 
        if mode:
            mode = int(mode, 8)
            assert stat.S_IMODE(st.st_mode) == mode
 
    def check_major_minor(self, st: os.stat_result) -> None:
        if not self.exp_major_minor:
            return
        minor, major = (int(x) for x in self.exp_major_minor.split(':'))
        assert st.st_rdev == os.makedev(minor, major)
 
    def get_devnode(self) -> Path:
        suffix = self.devnode if self.devnode else self.devpath.split('/')[-1]
        return UDEV_DEV / suffix
 
    def check_link_add(self, link: str, devnode: Path) -> None:
        link = UDEV_DEV / link
        tgt = link.parent / link.readlink()
        assert devnode.samefile(tgt)
 
    def check_link_nonexistent(self, link: str, devnode: Path) -> None:
        link = UDEV_DEV / link
 
        try:
            tgt = link.parent / link.readlink()
        except FileNotFoundError:
            return
 
        assert not devnode.samefile(tgt)
 
    def check_add(self) -> None:
        print(f'check_add {self.devpath}')
 
        devnode = self.get_devnode()
        st = devnode.lstat()
        assert stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode)
        self.check_permissions(st)
        self.check_major_minor(st)
 
        for link in self.exp_links or []:
            self.check_link_add(link, devnode)
 
        for link in self.not_exp_links or []:
            self.check_link_nonexistent(link, devnode)
 
    def check_link_remove(self, link: str) -> None:
        link = UDEV_DEV / link
        with pytest.raises(FileNotFoundError):
            link.readlink()
 
    def check_remove(self) -> None:
        devnode = self.get_devnode()
        assert not devnode.exists()
 
        for link in self.exp_links or []:
            self.check_link_remove(link)
 
 
def listify(f):
    def wrap(*args, **kwargs):
        return list(f(*args, **kwargs))
 
    return functools.update_wrapper(wrap, f)
 
 
@listify
def all_block_devs(exp_func) -> list[Device]:
    # Create a device list with all block devices under /sys
    # (except virtual devices and cd-roms)
    # the optional argument exp_func returns expected and non-expected
    # symlinks for the device.
 
    for p in UDEV_SYS.glob('dev/block/*'):
        tgt = os.readlink(p)
        if re.search('/virtual/ | /sr[0-9]*$', tgt, re.VERBOSE):
            continue
 
        assert tgt.startswith('../../')
        tgt = tgt[5:]
 
        exp, not_exp = exp_func(tgt)
        yield Device(devpath=tgt, exp_links=exp, not_exp_links=not_exp)
 
 
@dataclasses.dataclass
class Rules:
    desc: str
    devices: list[Device]
    rules: str
    device_generator: Callable = None
    repeat: int = 1
    delay: Optional[int] = None
 
    @classmethod
    def new(cls, desc: str, *devices, rules=None, device_generator=None, **kwargs):
        assert rules.startswith('\n')
        rules = textwrap.dedent(rules[1:]) if rules else ''
 
        assert bool(devices) ^ bool(device_generator)
 
        return cls(desc, devices, rules, device_generator=device_generator, **kwargs)
 
    def generate_devices(self) -> None:
        # We can't do this when the class is created, because setup is done later.
        if self.device_generator:
            self.devices = self.device_generator()
 
    def create_rules_file(self) -> None:
        # create temporary rules
        UDEV_RULES.parent.mkdir(exist_ok=True, parents=True)
        UDEV_RULES.write_text(self.rules)
 
 
RULES = [
    Rules.new(
        'no rules',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
        ),
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda1',
        ),
        rules=r'''
        #
        ''',
    ),
    Rules.new(
        'label test of scsi disc',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['boot_disk'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", SYMLINK+="boot_disk%n"
        KERNEL=="ttyACM0", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        'label test of scsi disc',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['boot_disk'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", SYMLINK+="boot_disk%n"
        KERNEL=="ttyACM0", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        'label test of scsi disc',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['boot_disk'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", SYMLINK+="boot_disk%n"
        KERNEL=="ttyACM0", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        'label test of scsi partition',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda1',
            exp_links=['boot_disk1'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", SYMLINK+="boot_disk%n"
        ''',
    ),
    Rules.new(
        'label test of pattern match',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda1',
            exp_links=['boot_disk1', 'boot_disk1-4', 'boot_disk1-5'],
            not_exp_links=['boot_disk1-1', 'boot_disk1-2', 'boot_disk1-3', 'boot_disk1-6', 'boot_disk1-7'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="?ATA", SYMLINK+="boot_disk%n-1"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA?", SYMLINK+="boot_disk%n-2"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="A??", SYMLINK+="boot_disk%n"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATAS", SYMLINK+="boot_disk%n-3"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="AT?", SYMLINK+="boot_disk%n-4"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="??A", SYMLINK+="boot_disk%n-5"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", GOTO="skip-6"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", SYMLINK+="boot_disk%n-6"
        LABEL="skip-6"
        SUBSYSTEMS=="scsi", GOTO="skip-7"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", SYMLINK+="boot_disk%n-7"
        LABEL="skip-7"
        ''',
    ),
    Rules.new(
        'label test of multiple sysfs files',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda1',
            exp_links=['boot_disk1'],
            not_exp_links=['boot_diskX1'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS X ", SYMLINK+="boot_diskX%n"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="boot_disk%n"
        ''',
    ),
    Rules.new(
        'label test of max sysfs files (skip invalid rule)',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda1',
            exp_links=['boot_disk1', 'boot_diskXY1'],
            not_exp_links=['boot_diskXX1'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", ATTRS{scsi_level}=="6", ATTRS{rev}=="4.06", ATTRS{type}=="0", ATTRS{queue_depth}=="32", SYMLINK+="boot_diskXX%n"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", ATTRS{scsi_level}=="6", ATTRS{rev}=="4.06", ATTRS{type}=="0", ATTRS{queue_depth}=="1", SYMLINK+="boot_diskXY%n"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", ATTRS{scsi_level}=="6", ATTRS{rev}=="4.06", ATTRS{type}=="0", SYMLINK+="boot_disk%n"
        ''',
    ),
    Rules.new(
        'SYMLINK tests',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda1',
            exp_links=[
                'link1',
                'link2/foo',
                'link3/aaa/bbb',
                'abs1',
                'abs2/foo',
                'abs3/aaa/bbb',
                'default___replace_test/foo_aaa',
                'string_escape___replace/foo_bbb',
                'env_with_space',
                'default/replace/mode_foo__hoge',
                'replace_env_harder_foo__hoge',
                'match',
                'unmatch',
            ],
            not_exp_links=[
                'removed1',
                'removed2',
                'removed3',
                'unsafe/../../path',
                '/nondev/path/will/be/refused',
            ],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="removed1"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK-="removed1"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="/./dev///removed2"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK-="removed2"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="././removed3"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK-="/dev//./removed3/./"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="unsafe/../../path"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="/nondev/path/will/be/refused"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="link1 .///link2/././/foo//./ .///link3/aaa/bbb"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="/dev/abs1 /dev//./abs2///foo/./ ////dev/abs3/aaa/bbb"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK+="default?;;replace%%test/foo'aaa"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", OPTIONS="string_escape=replace", SYMLINK+="string_escape   replace/foo%%bbb"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", ENV{.HOGE}="env    with    space", SYMLINK+="%E{.HOGE}"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", ENV{.HOGE}="default/replace/mode?foo;;hoge", SYMLINK+="%E{.HOGE}"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", OPTIONS="string_escape=replace", ENV{.HOGE}="replace/env/harder?foo;;hoge", SYMLINK+="%E{.HOGE}"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK=="link1", SYMLINK+="match"
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", ATTRS{model}=="ST910021AS", SYMLINK!="removed1", SYMLINK+="unmatch"
        ''',
    ),
    Rules.new(
        'catch device by *',
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem/0', 'catch-all'],
        ),
        rules=r'''
        KERNEL=="ttyACM*", SYMLINK+="modem/%n"
        KERNEL=="*", SYMLINK+="catch-all"
        ''',
    ),
    Rules.new(
        'catch device by * - take 2',
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem/0'],
            not_exp_links=['bad'],
        ),
        rules=r'''
        KERNEL=="*ACM1", SYMLINK+="bad"
        KERNEL=="*ACM0", SYMLINK+="modem/%n"
        ''',
    ),
    Rules.new(
        'catch device by ?',
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem/0'],
            not_exp_links=['modem/0-1', 'modem/0-2'],
        ),
        rules=r'''
        KERNEL=="ttyACM??*", SYMLINK+="modem/%n-1"
        KERNEL=="ttyACM??", SYMLINK+="modem/%n-2"
        KERNEL=="ttyACM?", SYMLINK+="modem/%n"
        ''',
    ),
    Rules.new(
        'catch device by character class',
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem/0'],
            not_exp_links=['modem/0-1', 'modem/0-2'],
        ),
        rules=r'''
        KERNEL=="ttyACM[A-Z]*", SYMLINK+="modem/%n-1"
        KERNEL=="ttyACM?[0-9]", SYMLINK+="modem/%n-2"
        KERNEL=="ttyACM[0-9]*", SYMLINK+="modem/%n"
        ''',
    ),
    Rules.new(
        "don't replace kernel name",
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem'],
        ),
        rules=r'''
        KERNEL=="ttyACM0", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        "comment lines in config file (and don't replace kernel name)",
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem'],
        ),
        rules=r'''
        # this is a comment
        KERNEL=="ttyACM0", SYMLINK+="modem"
 
        ''',
    ),
    Rules.new(
        "comment lines in config file with whitespace (and don't replace kernel name)",
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem'],
        ),
        rules=r'''
         # this is a comment with whitespace before the comment
        KERNEL=="ttyACM0", SYMLINK+="modem"
 
        ''',
    ),
    Rules.new(
        "whitespace only lines (and don't replace kernel name)",
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['whitespace'],
        ),
        rules=r'''
 
 
 
         # this is a comment with whitespace before the comment
        KERNEL=="ttyACM0", SYMLINK+="whitespace"
 
 
 
        ''',
    ),
    Rules.new(
        "empty lines in config file (and don't replace kernel name)",
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem'],
        ),
        rules=r'''
 
        KERNEL=="ttyACM0", SYMLINK+="modem"
 
        ''',
    ),
    Rules.new(
        "backslashed multi lines in config file (and don't replace kernel name)",
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem'],
        ),
        rules=r'''
        KERNEL=="ttyACM0", \
        SYMLINK+="modem"
 
        ''',
    ),
    Rules.new(
        'preserve backslashes, if they are not for a newline',
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['aaa'],
        ),
        rules=r'''
        KERNEL=="ttyACM0", PROGRAM=="/bin/echo -e \101", RESULT=="A", SYMLINK+="aaa"
        ''',
    ),
    Rules.new(
        "stupid backslashed multi lines in config file (and don't replace kernel name)",
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem'],
        ),
        rules=r'''
 
        #
        \
 
        \
 
        #\
 
        KERNEL=="ttyACM0", \
                SYMLINK+="modem"
 
        ''',
    ),
    Rules.new(
        'subdirectory handling',
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['sub/direct/ory/modem'],
        ),
        rules=r'''
        KERNEL=="ttyACM0", SYMLINK+="sub/direct/ory/modem"
        ''',
    ),
    Rules.new(
        'parent device name match of scsi partition',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['first_disk5'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", SYMLINK+="first_disk%n"
        ''',
    ),
    Rules.new(
        'test substitution chars',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['Major:8:minor:5:kernelnumber:5:id:0:0:0:0'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", SYMLINK+="Major:%M:minor:%m:kernelnumber:%n:id:%b"
        ''',
    ),
    Rules.new(
        'import of shell-value returned from program',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['node12345678'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", IMPORT{program}="/bin/echo -e ' TEST_KEY=12345678\n  TEST_key2=98765'", SYMLINK+="node$env{TEST_KEY}"
        KERNEL=="ttyACM0", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        'substitution of sysfs value (%s{file})',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['disk-ATA-sda'],
            not_exp_links=['modem'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{vendor}=="ATA", SYMLINK+="disk-%s{vendor}-%k"
        KERNEL=="ttyACM0", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        'program result substitution',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['special-device-5'],
            not_exp_links=['not'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n special-device", RESULT=="-special-*", SYMLINK+="not"
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n special-device", RESULT=="special-*", SYMLINK+="%c-%n"
        ''',
    ),
    Rules.new(
        'program result substitution (newline removal)',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['newline_removed'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo test", RESULT=="test", SYMLINK+="newline_removed"
        ''',
    ),
    Rules.new(
        'program result substitution',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['test-0:0:0:0'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n test-%b", RESULT=="test-0:0*", SYMLINK+="%c"
        ''',
    ),
    Rules.new(
        'program with lots of arguments',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['foo9'],
            not_exp_links=['foo3', 'foo4', 'foo5', 'foo6', 'foo7', 'foo8'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n foo3 foo4 foo5 foo6 foo7 foo8 foo9", KERNEL=="sda5", SYMLINK+="%c{7}"
        ''',
    ),
    Rules.new(
        'program with subshell',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['bar9'],
            not_exp_links=['foo3', 'foo4', 'foo5', 'foo6', 'foo7', 'foo8'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/bash -c 'echo foo3 foo4 foo5 foo6 foo7 foo8 foo9 | sed  s/foo9/bar9/'", KERNEL=="sda5", SYMLINK+="%c{7}"
        ''',
    ),
    Rules.new(
        'program arguments combined with apostrophes',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['foo7'],
            not_exp_links=['foo3', 'foo4', 'foo5', 'foo6', 'foo8'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n 'foo3 foo4'   'foo5   foo6   foo7 foo8'", KERNEL=="sda5", SYMLINK+="%c{5}"
        ''',
    ),
    Rules.new(
        'program arguments combined with escaped double quotes, part 1',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['foo2'],
            not_exp_links=['foo1'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/bash -c 'printf %%s \"foo1 foo2\" | grep \"foo1 foo2\"'", KERNEL=="sda5", SYMLINK+="%c{2}"
        ''',
    ),
    Rules.new(
        'program arguments combined with escaped double quotes, part 2',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['foo2'],
            not_exp_links=['foo1'],
        ),
        rules=r'''
SUBSYSTEMS=="scsi", PROGRAM=="/bin/bash -c \"printf %%s 'foo1 foo2' | grep 'foo1 foo2'\"", KERNEL=="sda5", SYMLINK+="%c{2}"
        ''',
    ),
    Rules.new(
        'program arguments combined with escaped double quotes, part 3',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['foo2'],
            not_exp_links=['foo1', 'foo3'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/bash -c 'printf \"%%s %%s\" \"foo1 foo2\" \"foo3\"| grep \"foo1 foo2\"'", KERNEL=="sda5", SYMLINK+="%c{2}"
        ''',
    ),
    Rules.new(
        'characters before the %c{N} substitution',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['my-foo9'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n foo3 foo4 foo5 foo6 foo7 foo8 foo9", KERNEL=="sda5", SYMLINK+="my-%c{7}"
        ''',
    ),
    Rules.new(
        'substitute the second to last argument',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['my-foo8'],
            not_exp_links=['my-foo3', 'my-foo4', 'my-foo5', 'my-foo6', 'my-foo7', 'my-foo9'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n foo3 foo4 foo5 foo6 foo7 foo8 foo9", KERNEL=="sda5", SYMLINK+="my-%c{6}"
        ''',
    ),
    Rules.new(
        'test substitution by variable name',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['Major:8-minor:5-kernelnumber:5-id:0:0:0:0'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", SYMLINK+="Major:$major-minor:$minor-kernelnumber:$number-id:$id"
        ''',
    ),
    Rules.new(
        'test substitution by variable name 2',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['Major:8-minor:5-kernelnumber:5-id:0:0:0:0'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", DEVPATH=="*/sda/*", SYMLINK+="Major:$major-minor:%m-kernelnumber:$number-id:$id"
        ''',
    ),
    Rules.new(
        'test substitution by variable name 3',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['850:0:0:05'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", DEVPATH=="*/sda/*", SYMLINK+="%M%m%b%n"
        ''',
    ),
    Rules.new(
        'test substitution by variable name 4',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['855'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", DEVPATH=="*/sda/*", SYMLINK+="$major$minor$number"
        ''',
    ),
    Rules.new(
        'test substitution by variable name 5',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda/sda5',
            exp_links=['8550:0:0:0'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", DEVPATH=="*/sda/*", SYMLINK+="$major%m%n$id"
        ''',
    ),
    Rules.new(
        'non matching SUBSYSTEMS for device with no parent',
        Device(
            '/devices/virtual/tty/console',
            exp_links=['TTY'],
            not_exp_links=['foo'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n foo", RESULT=="foo", SYMLINK+="foo"
        KERNEL=="console", SYMLINK+="TTY"
        ''',
    ),
    Rules.new(
        'non matching SUBSYSTEMS',
        Device(
            '/devices/virtual/tty/console',
            exp_links=['TTY'],
            not_exp_links=['foo'],
        ),
        rules=r'''
        SUBSYSTEMS=="foo", ATTRS{dev}=="5:1", SYMLINK+="foo"
        KERNEL=="console", SYMLINK+="TTY"
        ''',
    ),
    Rules.new(
        'ATTRS match',
        Device(
            '/devices/virtual/tty/console',
            exp_links=['foo', 'TTY'],
        ),
        rules=r'''
        KERNEL=="console", SYMLINK+="TTY"
        ATTRS{dev}=="5:1", SYMLINK+="foo"
        ''',
    ),
    Rules.new(
        'ATTR (empty file)',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['empty', 'not-something'],
            not_exp_links=['something', 'not-empty'],
        ),
        rules=r'''
        KERNEL=="sda", ATTR{test_empty_file}=="?*", SYMLINK+="something"
        KERNEL=="sda", ATTR{test_empty_file}!="", SYMLINK+="not-empty"
        KERNEL=="sda", ATTR{test_empty_file}=="", SYMLINK+="empty"
        KERNEL=="sda", ATTR{test_empty_file}!="?*", SYMLINK+="not-something"
        ''',
    ),
    Rules.new(
        'ATTR (non-existent file)',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['non-existent', 'wrong'],
            not_exp_links=['something', 'empty', 'not-empty', 'not-something', 'something'],
        ),
        rules=r'''
        KERNEL=="sda", ATTR{nofile}=="?*", SYMLINK+="something"
        KERNEL=="sda", ATTR{nofile}!="", SYMLINK+="not-empty"
        KERNEL=="sda", ATTR{nofile}=="", SYMLINK+="empty"
        KERNEL=="sda", ATTR{nofile}!="?*", SYMLINK+="not-something"
        KERNEL=="sda", TEST!="nofile", SYMLINK+="non-existent"
        KERNEL=="sda", SYMLINK+="wrong"
        ''',
    ),
    Rules.new(
        'program and bus type match',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['scsi-0:0:0:0'],
        ),
        rules=r'''
        SUBSYSTEMS=="usb", PROGRAM=="/bin/echo -n usb-%b", SYMLINK+="%c"
        SUBSYSTEMS=="scsi", PROGRAM=="/bin/echo -n scsi-%b", SYMLINK+="%c"
        SUBSYSTEMS=="foo", PROGRAM=="/bin/echo -n foo-%b", SYMLINK+="%c"
        ''',
    ),
    Rules.new(
        'sysfs parent hierarchy',
        Device(
            '/devices/pci0000:00/0000:00:1d.7/usb5/5-2/5-2:1.0/tty/ttyACM0',
            exp_links=['modem'],
        ),
        rules=r'''
        ATTRS{idProduct}=="007b", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        'name test with ! in the name',
        Device(
            '/devices/virtual/block/fake!blockdev0',
            devnode='fake/blockdev0',
            exp_links=['is/a/fake/blockdev0'],
            not_exp_links=['is/not/a/fake/blockdev0', 'modem'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", SYMLINK+="is/not/a/%k"
        SUBSYSTEM=="block", SYMLINK+="is/a/%k"
        KERNEL=="ttyACM0", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        'name test with ! in the name, but no matching rule',
        Device(
            '/devices/virtual/block/fake!blockdev0',
            devnode='fake/blockdev0',
            not_exp_links=['modem'],
        ),
        rules=r'''
        KERNEL=="ttyACM0", SYMLINK+="modem"
        ''',
    ),
    Rules.new(
        'KERNELS rule',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['scsi-0:0:0:0'],
            not_exp_links=['no-match', 'short-id', 'not-scsi'],
        ),
        rules=r'''
        SUBSYSTEMS=="usb", KERNELS=="0:0:0:0", SYMLINK+="not-scsi"
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:1", SYMLINK+="no-match"
        SUBSYSTEMS=="scsi", KERNELS==":0", SYMLINK+="short-id"
        SUBSYSTEMS=="scsi", KERNELS=="/0:0:0:0", SYMLINK+="no-match"
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", SYMLINK+="scsi-0:0:0:0"
        ''',
    ),
    Rules.new(
        'KERNELS wildcard all',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['scsi-0:0:0:0'],
            not_exp_links=['no-match', 'before'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="*:1", SYMLINK+="no-match"
        SUBSYSTEMS=="scsi", KERNELS=="*:0:1", SYMLINK+="no-match"
        SUBSYSTEMS=="scsi", KERNELS=="*:0:0:1", SYMLINK+="no-match"
        SUBSYSTEMS=="scsi", KERNEL=="0:0:0:0", SYMLINK+="before"
        SUBSYSTEMS=="scsi", KERNELS=="*", SYMLINK+="scsi-0:0:0:0"
        ''',
    ),
    Rules.new(
        'KERNELS wildcard partial',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['scsi-0:0:0:0', 'before'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", SYMLINK+="before"
        SUBSYSTEMS=="scsi", KERNELS=="*:0", SYMLINK+="scsi-0:0:0:0"
        ''',
    ),
    Rules.new(
        'KERNELS wildcard partial 2',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['scsi-0:0:0:0', 'before'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNELS=="0:0:0:0", SYMLINK+="before"
        SUBSYSTEMS=="scsi", KERNELS=="*:0:0:0", SYMLINK+="scsi-0:0:0:0"
        ''',
    ),
    Rules.new(
        'substitute attr with link target value (first match)',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['driver-is-sd'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", SYMLINK+="driver-is-$attr{driver}"
        ''',
    ),
    Rules.new(
        'substitute attr with link target value (currently selected device)',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['driver-is-ahci'],
        ),
        rules=r'''
        SUBSYSTEMS=="pci", SYMLINK+="driver-is-$attr{driver}"
        ''',
    ),
    Rules.new(
        'ignore ATTRS attribute whitespace',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['ignored'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{whitespace_test}=="WHITE  SPACE", SYMLINK+="ignored"
        ''',
    ),
    Rules.new(
        'do not ignore ATTRS attribute whitespace',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['matched-with-space'],
            not_exp_links=['wrong-to-ignore'],
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", ATTRS{whitespace_test}=="WHITE  SPACE ", SYMLINK+="wrong-to-ignore"
        SUBSYSTEMS=="scsi", ATTRS{whitespace_test}=="WHITE  SPACE   ", SYMLINK+="matched-with-space"
        ''',
    ),
    Rules.new(
        'permissions USER=bad GROUP=name',
        Device(
            '/devices/virtual/tty/tty33',
            exp_perms='0:0:0600',
        ),
        rules=r'''
        KERNEL=="tty33", OWNER="bad", GROUP="name"
        ''',
    ),
    Rules.new(
        'permissions OWNER=1',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['node'],
            exp_perms='1::0600',
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNEL=="sda", SYMLINK+="node", OWNER="1"
        ''',
    ),
    Rules.new(
        'permissions GROUP=1',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['node'],
            exp_perms=':1:0660',
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNEL=="sda", SYMLINK+="node", GROUP="1"
        ''',
    ),
    Rules.new(
        'textual user id',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['node'],
            exp_perms='daemon::0600',
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNEL=="sda", SYMLINK+="node", OWNER="daemon"
        ''',
    ),
    Rules.new(
        'textual group id',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['node'],
            exp_perms=':daemon:0660',
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNEL=="sda", SYMLINK+="node", GROUP="daemon"
        ''',
    ),
    Rules.new(
        'textual user/group id',
        Device(
            '/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda',
            exp_links=['node'],
            exp_perms='root:audio:0660',
        ),
        rules=r'''
        SUBSYSTEMS=="scsi", KERNEL=="sda", SYMLINK+="node", OWNER="root", GROUP="audio"