File: test_orgexamplemore.py

package info (click to toggle)
python-varlink 32.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 328 kB
  • sloc: python: 2,705; sh: 177; makefile: 29
file content (269 lines) | stat: -rwxr-xr-x 8,178 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/env python

"""Server and Client example of varlink for python

From the main git repository directory run::

    $ PYTHONPATH=$(pwd) python3 ./varlink/tests/test_orgexamplemore.py

or::

    $ PYTHONPATH=$(pwd) python3 ./varlink/tests/test_orgexamplemore.py --varlink="unix:@test" &
    Listening on @test
    [1] 6434
    $ PYTHONPATH=$(pwd) python3 ./varlink/tests/test_orgexamplemore.py --client --varlink="unix:@test"
    [...]

"""

import argparse
import os
import shlex
import socket
import sys
import textwrap
import threading
import time
import unittest
from sys import platform

import varlink

######## CLIENT #############


def run_client(client):
    print(f"Connecting to {client}\n")
    try:
        with (
            client.open("org.example.more", namespaced=True) as con1,
            client.open("org.example.more", namespaced=True) as con2,
        ):
            for m in con1.TestMore(10, _more=True):
                if hasattr(m.state, "start") and m.state.start is not None:
                    if m.state.start:
                        print("--- Start ---", file=sys.stderr)

                if hasattr(m.state, "end") and m.state.end is not None:
                    if m.state.end:
                        print("--- End ---", file=sys.stderr)

                if hasattr(m.state, "progress") and m.state.progress is not None:
                    print("Progress:", m.state.progress, file=sys.stderr)
                    if m.state.progress > 50:
                        ret = con2.Ping("Test")
                        print("Ping: ", ret.pong)

    except ConnectionError as e:
        print("ConnectionError:", e)
        raise e
    except varlink.VarlinkError as e:
        print(e)
        print(e.error())
        print(e.parameters())
        raise e


######## SERVER #############

service = varlink.Service(
    vendor="Varlink",
    product="Varlink Examples",
    version="1",
    url="http://varlink.org",
    interface_dir=os.path.dirname(__file__),
)


class ServiceRequestHandler(varlink.RequestHandler):
    service = service


class ActionFailed(varlink.VarlinkError):
    def __init__(self, reason):
        varlink.VarlinkError.__init__(
            self, {"error": "org.example.more.ActionFailed", "parameters": {"field": reason}}
        )


@service.interface("org.example.more")
class Example:
    sleep_duration = 1.0

    def TestMore(self, n, _more=True, _server=None):
        try:
            if not _more:
                yield varlink.InvalidParameter("more")

            yield {"state": {"start": True}, "_continues": True}

            for i in range(0, n):
                yield {"state": {"progress": int(i * 100 / n)}, "_continues": True}
                time.sleep(self.sleep_duration)

            yield {"state": {"progress": 100}, "_continues": True}

            yield {"state": {"end": True}, "_continues": False}
        except Exception as error:
            print("ERROR", error, file=sys.stderr)
            if _server:
                _server.shutdown()

    def Ping(self, ping):
        return {"pong": ping}

    def StopServing(self, reason=None, _request=None, _server=None):
        print("Server ends.")

        if _request:
            print("Shutting down client connection")
            _server.shutdown_request(_request)

        if _server:
            print("Shutting down server")
            _server.shutdown()

    def TestMap(self, map):
        i = 1
        ret = {}
        for key, val in map.items():
            ret[key] = {"i": i, "val": val}
            i += 1
        return {"map": ret}

    def TestObject(self, object):
        import json

        return {"object": json.loads(json.dumps(object))}


def run_server(address):
    with varlink.ThreadingServer(address, ServiceRequestHandler) as server:
        print("Listening on", server.server_address)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass


######## MAIN #############


def epilog():
    arg0 = sys.argv[0]
    return textwrap.dedent(
        f"""
    Examples:
        \tSelf Exec: $ {arg0}
        \tServer   : $ {arg0} --varlink=<varlink address>
        \tClient   : $ {arg0} --client --varlink=<varlink address>
        \tClient   : $ {arg0} --client --bridge=<bridge command>
        \tClient   : $ {arg0} --client --activate=<activation command>
    """
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Varlink org.example.more test case",
        epilog=epilog(),
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument("--varlink", type=str, help="The varlink address")
    parser.add_argument("-b", "--bridge", type=str, help="bridge command")
    parser.add_argument("-A", "--activate", type=str, help="activation command")
    parser.add_argument("--client", action="store_true", help="launch the client mode")
    args = parser.parse_args()

    address = args.varlink
    client_mode = args.client
    activate = args.activate
    bridge = args.bridge

    client = None

    if client_mode:
        if bridge:
            client = varlink.Client.new_with_bridge(shlex.split(bridge))
        if activate:
            client = varlink.Client.new_with_activate(shlex.split(activate))
        if address:
            client = varlink.Client.new_with_address(address)

    if not address and not client_mode:
        if not hasattr(socket, "AF_UNIX"):
            print(f"varlink activate: not supported on platform {platform}", file=sys.stderr)
            parser.print_help()
            sys.exit(2)

        client_mode = True
        with varlink.Client.new_with_activate([__file__, "--varlink=$VARLINK_ADDRESS"]) as client:
            run_client(client)
    elif client_mode:
        if client is None:
            raise ValueError("--client requires at either of --varlink, --bridge or --activate")
        with client:
            run_client(client)
    else:
        run_server(address)

    sys.exit(0)


######## UNITTEST #############


class TestService(unittest.TestCase):
    def test_service(self) -> None:
        address = "tcp:127.0.0.1:23451"
        Example.sleep_duration = 0.1

        server = varlink.ThreadingServer(address, ServiceRequestHandler)
        server_thread = threading.Thread(target=server.serve_forever)
        server_thread.daemon = True
        server_thread.start()
        try:
            client = varlink.Client.new_with_address(address)

            run_client(client)

            with (
                client.open("org.example.more", namespaced=True) as con1,
                client.open("org.example.more", namespaced=True) as con2,
            ):
                self.assertEqual(con1.Ping("Test").pong, "Test")

                it = con1.TestMore(10, _more=True)

                m = next(it)
                self.assertTrue(hasattr(m.state, "start"))
                self.assertFalse(hasattr(m.state, "end"))
                self.assertFalse(hasattr(m.state, "progress"))
                self.assertIsNotNone(m.state.start)

                for i in range(0, 110, 10):
                    m = next(it)
                    self.assertTrue(hasattr(m.state, "progress"))
                    self.assertFalse(hasattr(m.state, "start"))
                    self.assertFalse(hasattr(m.state, "end"))
                    self.assertIsNotNone(m.state.progress)
                    self.assertEqual(i, m.state.progress)

                    if i > 50:
                        ret = con2.Ping("Test")
                        self.assertEqual("Test", ret.pong)

                m = next(it)
                self.assertTrue(hasattr(m.state, "end"))
                self.assertFalse(hasattr(m.state, "start"))
                self.assertFalse(hasattr(m.state, "progress"))
                self.assertIsNotNone(m.state.end)

                self.assertRaises(StopIteration, next, it)

                con1.StopServing(_oneway=True)
                time.sleep(0.5)
                self.assertRaises(ConnectionError, con1.Ping, "Test")
        finally:
            server.shutdown()
            server.server_close()