| 1 |
import datetime |
| 2 |
import inspect |
| 3 |
import os |
| 4 |
import subprocess |
| 5 |
import sys |
| 6 |
import textwrap |
| 7 |
import time |
| 8 |
import uuid |
| 9 |
|
| 10 |
import varlink |
| 11 |
|
| 12 |
|
| 13 |
def cast_type(typeof): |
| 14 |
cast = {"str": "string"} |
| 15 |
typeof = str(typeof).replace("<class '", "").replace("'>", "") |
| 16 |
return cast.get(typeof, typeof) |
| 17 |
|
| 18 |
|
| 19 |
def get_ignored() -> list[str]: |
| 20 |
ignore = dir(MockedService) |
| 21 |
return ignore |
| 22 |
|
| 23 |
|
| 24 |
def get_interface_attributs(interface, ignored): |
| 25 |
attributs = {"callables": [], "others": []} |
| 26 |
for attr in dir(interface): |
| 27 |
if attr in ignored: |
| 28 |
continue |
| 29 |
attribut = getattr(interface, attr) |
| 30 |
if callable(attribut): |
| 31 |
attributs["callables"].append(attr) |
| 32 |
else: |
| 33 |
attributs["others"].append(attr) |
| 34 |
return attributs |
| 35 |
|
| 36 |
|
| 37 |
def generate_callable_interface(interface, attr): |
| 38 |
attribut = getattr(interface, attr) |
| 39 |
signature = inspect.signature(attribut) |
| 40 |
params = signature.parameters.values() |
| 41 |
sign = [] |
| 42 |
for param in params: |
| 43 |
if param.name == "self": |
| 44 |
continue |
| 45 |
typeof = param.annotation |
| 46 |
sign.append(f"{param.name}: {cast_type(typeof)}") |
| 47 |
returned = signature.return_annotation |
| 48 |
if returned: |
| 49 |
returned = cast_type(returned) |
| 50 |
doc = attribut.__doc__ |
| 51 |
if not doc: |
| 52 |
raise ValueError("docstring format must be:return name: type") |
| 53 |
doc = doc.replace("return ", "") |
| 54 |
if ":" in doc: |
| 55 |
returned = doc |
| 56 |
else: |
| 57 |
returned = f"{doc}: {returned}" |
| 58 |
else: |
| 59 |
returned = "" |
| 60 |
return f"method {attr}({','.join(sign)}) -> ({returned})" |
| 61 |
|
| 62 |
|
| 63 |
class MockedServiceProcess: |
| 64 |
address = None |
| 65 |
vendor = None |
| 66 |
product = None |
| 67 |
version = None |
| 68 |
url = None |
| 69 |
interface = None |
| 70 |
interface_file = None |
| 71 |
interface_name = None |
| 72 |
interface_content = None |
| 73 |
service_to_mock = None |
| 74 |
|
| 75 |
def run(self): |
| 76 |
mocked_service = varlink.Service( |
| 77 |
vendor=self.vendor, |
| 78 |
product=self.product, |
| 79 |
version=self.version, |
| 80 |
url=self.url, |
| 81 |
) |
| 82 |
instanciated_service = self.service_to_mock() |
| 83 |
mocked_service._set_interface(self.interface_file, instanciated_service) |
| 84 |
|
| 85 |
class ServiceRequestHandler(varlink.RequestHandler): |
| 86 |
service = mocked_service |
| 87 |
|
| 88 |
self.varlink_server = varlink.ThreadingServer(self.address, ServiceRequestHandler) |
| 89 |
self.varlink_server.serve_forever() |
| 90 |
|
| 91 |
|
| 92 |
def service_generator(service, info, filename="mockedservice.py"): |
| 93 |
with open(filename, "w+") as pyfp: |
| 94 |
pyfp.write( |
| 95 |
textwrap.dedent( |
| 96 |
f"""\ |
| 97 |
''' |
| 98 |
Generated by varlink mocking system |
| 99 |
|
| 100 |
{datetime.datetime.now()} |
| 101 |
Only for testing purpose and unit testing |
| 102 |
''' |
| 103 |
""" |
| 104 |
) |
| 105 |
) |
| 106 |
pyfp.write("import varlink\n\n") |
| 107 |
pyfp.write(inspect.getsource(service)) |
| 108 |
pyfp.write("\n\n") |
| 109 |
pyfp.write(inspect.getsource(MockedServiceProcess)) |
| 110 |
pyfp.write("\n\n") |
| 111 |
pyfp.write("if __name__ == '__main__':\n") |
| 112 |
pyfp.write(" msp = MockedServiceProcess()\n") |
| 113 |
for key, value in info.items(): |
| 114 |
surround = "'" |
| 115 |
if value["type"] == "raw": |
| 116 |
surround = "" |
| 117 |
pyfp.write(f" msp.{key} = {surround}{value['value']}{surround}\n") |
| 118 |
pyfp.write(" msp.run()\n") |
| 119 |
|
| 120 |
|
| 121 |
def mockedservice( |
| 122 |
fake_service=None, |
| 123 |
fake_types=None, |
| 124 |
address="unix:@test", |
| 125 |
name=None, |
| 126 |
vendor="varlink", |
| 127 |
product="mock", |
| 128 |
version=1, |
| 129 |
url="http://localhost", |
| 130 |
): |
| 131 |
""" |
| 132 |
Varlink mocking service |
| 133 |
|
| 134 |
To mock a fake service and merely test your varlink client against. |
| 135 |
|
| 136 |
The mocking feature is for testing purpose, it's allow |
| 137 |
you to test your varlink client against a fake service which will |
| 138 |
returned self handed result defined in your object who will be mocked. |
| 139 |
|
| 140 |
Example: |
| 141 |
|
| 142 |
>>> import unittest |
| 143 |
>>> from varlink import mock |
| 144 |
>>> import varlink |
| 145 |
>>> |
| 146 |
>>> |
| 147 |
>>> types = ''' |
| 148 |
>>> type MyPersonalType ( |
| 149 |
>>> foo: string, |
| 150 |
>>> bar: string, |
| 151 |
>>> ) |
| 152 |
>>> ''' |
| 153 |
>>> |
| 154 |
>>> |
| 155 |
>>> class Service(): |
| 156 |
>>> |
| 157 |
>>> def Test1(self, param1: int) -> dict: |
| 158 |
>>> ''' |
| 159 |
>>> return test: MyPersonalType |
| 160 |
>>> ''' |
| 161 |
>>> return { |
| 162 |
>>> "test": { |
| 163 |
>>> "foo": "bim", |
| 164 |
>>> "bar": "boom" |
| 165 |
>>> } |
| 166 |
>>> } |
| 167 |
>>> |
| 168 |
>>> def Test2(self, param1: str) -> dict: |
| 169 |
>>> ''' |
| 170 |
>>> return (test: string) |
| 171 |
>>> ''' |
| 172 |
>>> return {"test": param1} |
| 173 |
>>> |
| 174 |
>>> def Test3(self, param1: int) -> dict: |
| 175 |
>>> ''' |
| 176 |
>>> return (test: int, boom: string, foo: string, bar: 42) |
| 177 |
>>> ''' |
| 178 |
>>> return { |
| 179 |
>>> "test": param1 * 2, |
| 180 |
>>> "boom": "foo", |
| 181 |
>>> "foo": "bar", |
| 182 |
>>> "bar": 42, |
| 183 |
>>> } |
| 184 |
>>> |
| 185 |
>>> |
| 186 |
>>> class TestMyClientWithMockedService(unittest.TestCase): |
| 187 |
>>> |
| 188 |
>>> @mock.mockedservice( |
| 189 |
>>> fake_service=Service, |
| 190 |
>>> fake_types=types, |
| 191 |
>>> name='org.service.com', |
| 192 |
>>> address='unix:@foo' |
| 193 |
>>> ) |
| 194 |
>>> def test_my_client_against_a_mock(self): |
| 195 |
>>> with varlink.Client("unix:@foo") as client: |
| 196 |
>>> connection = client.open('org.service.com') |
| 197 |
>>> self.assertEqual( |
| 198 |
>>> connection.Test1(param1=1)["test"]["bar"], "boom") |
| 199 |
>>> self.assertEqual( |
| 200 |
>>> connection.Test2(param1="foo")["test"], "foo") |
| 201 |
>>> self.assertEqual( |
| 202 |
>>> connection.Test3(param1=6)["test"], 12) |
| 203 |
>>> self.assertEqual( |
| 204 |
>>> connection.Test3(param1=6)["bar"], 42) |
| 205 |
|
| 206 |
First you need to define a sample class that will be passed to your |
| 207 |
decorator `mock.mockedservice` and then a service will be initialized |
| 208 |
and launched automatically, and after that you just need to connect your |
| 209 |
client to him and to establish your connection then now you can |
| 210 |
call your methods and it will give you the expected result. |
| 211 |
|
| 212 |
You can also mock some types too, to help you to mock more complex service |
| 213 |
and interfaces like podman by example. |
| 214 |
|
| 215 |
You can define the return type by using the method docstring like |
| 216 |
the method Test1 in our previous example. |
| 217 |
|
| 218 |
The mocking module is only compatible with python 3 or higher version |
| 219 |
of python because this module require annotation to generate interface |
| 220 |
description. |
| 221 |
|
| 222 |
If you try to use it with python 2.x it will raise an ``ImportError``. |
| 223 |
""" |
| 224 |
|
| 225 |
def decorator(func): |
| 226 |
def wrapper(*args, **kwargs): |
| 227 |
with MockedService(fake_service, fake_types, name=name, address=address): |
| 228 |
try: |
| 229 |
func(*args, **kwargs) |
| 230 |
except BrokenPipeError: |
| 231 |
# manage fake service stopping |
| 232 |
pass |
| 233 |
return |
| 234 |
|
| 235 |
return wrapper |
| 236 |
|
| 237 |
return decorator |
| 238 |
|
| 239 |
|
| 240 |
class MockedService: |
| 241 |
def __init__( |
| 242 |
self, |
| 243 |
service, |
| 244 |
types, |
| 245 |
address="unix:@test", |
| 246 |
name=None, |
| 247 |
vendor="varlink", |
| 248 |
product="mock", |
| 249 |
version=1, |
| 250 |
url="http://localhost", |
| 251 |
) -> None: |
| 252 |
if not name: |
| 253 |
module = service.__module__ |
| 254 |
try: |
| 255 |
self.name = os.path.splitext(module)[1].replace(".", "") |
| 256 |
except IndexError: |
| 257 |
self.name = module |
| 258 |
else: |
| 259 |
self.name = name |
| 260 |
self.identifier = str(uuid.uuid4()) |
| 261 |
self.interface_description: list[str] = [] |
| 262 |
self.service = service |
| 263 |
self.types = types |
| 264 |
self.address = address |
| 265 |
self.vendor = vendor |
| 266 |
self.product = product |
| 267 |
self.version = version |
| 268 |
self.url = url |
| 269 |
self.service_info = { |
| 270 |
"address": {"type": "inherited", "value": address}, |
| 271 |
"vendor": {"type": "inherited", "value": vendor}, |
| 272 |
"product": {"type": "inherited", "value": product}, |
| 273 |
"version": {"type": "raw", "value": version}, |
| 274 |
"url": {"type": "inherited", "value": url}, |
| 275 |
"interface_name": {"type": "inherited", "value": self.name}, |
| 276 |
"interface_file": {"type": "inherited", "value": self.get_interface_file_path()}, |
| 277 |
"service_to_mock": {"type": "raw", "value": service.__name__}, |
| 278 |
} |
| 279 |
self.generate_interface() |
| 280 |
|
| 281 |
def generate_interface(self) -> None: |
| 282 |
ignore = get_ignored() |
| 283 |
self.interface_description = [f"interface {self.name}"] |
| 284 |
if self.types: |
| 285 |
for line in self.types.split("\n"): |
| 286 |
self.interface_description.append(line) |
| 287 |
attributs = get_interface_attributs(self.service, ignore) |
| 288 |
for attr in attributs["callables"]: |
| 289 |
self.interface_description.append(generate_callable_interface(self.service, attr)) |
| 290 |
|
| 291 |
def get_interface_file_path(self) -> str: |
| 292 |
return f"/tmp/{self.name}" |
| 293 |
|
| 294 |
def generate_interface_file(self) -> None: |
| 295 |
tfp = open(self.get_interface_file_path(), "w+") |
| 296 |
tfp.write("\n".join(self.interface_description)) |
| 297 |
tfp.close() |
| 298 |
|
| 299 |
def delete_interface_files(self) -> None: |
| 300 |
os.remove(self.get_interface_file_path()) |
| 301 |
os.remove(self.mocked_service_file) |
| 302 |
|
| 303 |
def service_start(self) -> None: |
| 304 |
self.service_pid = subprocess.Popen( |
| 305 |
[sys.executable, self.mocked_service_file], env={"PYTHONPATH": ":".join(sys.path)} |
| 306 |
) |
| 307 |
time.sleep(2) |
| 308 |
|
| 309 |
def service_stop(self) -> None: |
| 310 |
self.service_pid.kill() |
| 311 |
self.service_pid.communicate() |
| 312 |
|
| 313 |
def __enter__(self): |
| 314 |
self.mocked_service_file = f"/tmp/{self.identifier}" |
| 315 |
service_generator(self.service, self.service_info, filename=self.mocked_service_file) |
| 316 |
self.generate_interface_file() |
| 317 |
self.service_start() |
| 318 |
return self |
| 319 |
|
| 320 |
def __exit__(self, type, value, traceback): |
| 321 |
self.service_stop() |
| 322 |
self.delete_interface_files() |