testutil: extract find_one_subclass_in_module() helper
A small refactor to avoid shipping this duplicated code (this one is easy to extract/reuse).
This commit is contained in:
parent
79360b529a
commit
1d4f2dc53b
3 changed files with 22 additions and 20 deletions
|
|
@ -2,6 +2,7 @@
|
|||
Test related utilities
|
||||
"""
|
||||
import contextlib
|
||||
import inspect
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
|
|
@ -10,6 +11,8 @@ import socket
|
|||
import subprocess
|
||||
import tempfile
|
||||
import textwrap
|
||||
from types import ModuleType
|
||||
from typing import Type
|
||||
|
||||
|
||||
def has_executable(executable: str) -> bool:
|
||||
|
|
@ -168,3 +171,18 @@ def make_fake_service_fd() -> int:
|
|||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
|
||||
fd = os.dup(sock.fileno())
|
||||
return fd
|
||||
|
||||
|
||||
def find_one_subclass_in_module(module: ModuleType, subclass: Type) -> object:
|
||||
"""Find the class in the given module that is a subclass of the given input
|
||||
|
||||
If multiple classes are found an error is raised.
|
||||
"""
|
||||
cls = None
|
||||
for name, memb in inspect.getmembers(
|
||||
module,
|
||||
predicate=lambda obj: inspect.isclass(obj) and issubclass(obj, subclass)):
|
||||
if cls:
|
||||
raise ValueError(f"already have {cls}, also found {name}:{memb}")
|
||||
cls = memb
|
||||
return cls
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue