File: test_simulator_api.py

package info (click to toggle)
pymodbus 3.8.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,720 kB
  • sloc: python: 14,867; makefile: 27; sh: 17
file content (478 lines) | stat: -rw-r--r-- 17,389 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
"""Test simulator API."""
import asyncio
import json

import pytest
from aiohttp import ClientSession

from pymodbus.server import ModbusSimulatorServer
from pymodbus.server.simulator import http_server


class TestSimulatorApi:
    """Integration tests for the pymodbus.SimutorServer module."""

    default_config = {
        "server_list": {
            "test-device-server": {
                # The test does not care about the server configuration, but
                # they must be present for the simulator to start.
                "comm": "tcp",
                "host": "0.0.0.0",
                "port": 25020,
                "framer": "socket",
            }
        },
        "device_list": {
            "test-device": {
                "setup": {
                    "co size": 100,
                    "di size": 150,
                    "hr size": 200,
                    "ir size": 250,
                    "shared blocks": True,
                    "type exception": False,
                    "defaults": {
                        "value": {
                            "bits": 0x0708,
                            "uint16": 1,
                            "uint32": 45000,
                            "float32": 127.4,
                            "string": "X",
                        },
                        "action": {
                            "bits": None,
                            "uint16": None,
                            "uint32": None,
                            "float32": None,
                            "string": None,
                        },
                    },
                },
                "invalid": [
                    1,
                    [3, 4],
                ],
                "write": [
                    5,
                    [7, 8],
                    [16, 18],
                    [21, 26],
                    [33, 38],
                ],
                "bits": [
                    5,
                    [7, 8],
                    {"addr": 10, "value": 0x81},
                    {"addr": [11, 12], "value": 0x04342},
                    {"addr": 13, "action": "random"},
                    {"addr": 14, "value": 15, "action": "reset"},
                ],
                "uint16": [
                    {"addr": 16, "value": 3124},
                    {"addr": [17, 18], "value": 5678},
                    {
                        "addr": [19, 20],
                        "value": 14661,
                        "action": "increment",
                        "args": {"minval": 1, "maxval": 100},
                    },
                ],
                "uint32": [
                    {"addr": [21, 22], "value": 3124},
                    {"addr": [23, 26], "value": 5678},
                    {"addr": [27, 30], "value": 345000, "action": "increment"},
                    {
                        "addr": [31, 32],
                        "value": 50,
                        "action": "random",
                        "parameters": {"minval": 10, "maxval": 80},
                    },
                ],
                "float32": [
                    {"addr": [33, 34], "value": 3124.5},
                    {"addr": [35, 38], "value": 5678.19},
                    {"addr": [39, 42], "value": 345000.18, "action": "increment"},
                ],
                "string": [
                    {"addr": [43, 44], "value": "Str"},
                    {"addr": [45, 48], "value": "Strxyz12"},
                ],
                "repeat": [{"addr": [0, 48], "to": [49, 147]}],
            }
        }
    }

    # Fixture to set up the aiohttp app
    @pytest.fixture
    async def client(self, aiohttp_client, tmp_path):
        """Fixture to provide usable aiohttp client for testing."""
        async with ClientSession() as session:
            yield session

    @pytest.fixture
    async def simulator(self, tmp_path):
        """Fixture to provide a standard simulator for testing."""
        config_path = tmp_path / "config.json"
        # Dump the config to a json file for the simulator
        with open(config_path, "w") as file:
            json.dump(self.default_config, file)

        simulator = ModbusSimulatorServer(
            modbus_server = "test-device-server",
            modbus_device = "test-device",
            http_host = "localhost",
            http_port = 18080,
            log_file = "simulator.log",
            json_file = config_path
        )

        # Run the simulator in the current event loop. Store the task so they live
        # until the test is done.
        loop = asyncio.get_running_loop()
        task = loop.create_task(simulator.run_forever(only_start=True))

        # TODO: Make a better way to wait for the simulator to start
        await asyncio.sleep(1)

        yield simulator

        # Stop the simulator after the test is done
        task.cancel()
        await task
        await simulator.stop()

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_registers_json_valid(self, client, simulator):
        """Test the /restapi/registers endpoint with valid parameters."""
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/registers"
        data = {
            "submit": "Registers",
            "range_start": 16,
            "range_stop": 16,
        }

        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()

            assert "result" in json_response
            assert "footer" in json_response
            assert "register_types" in json_response
            assert "register_actions" in json_response
            assert "register_rows" in json_response

            assert json_response["result"] == "ok"

            # Check that we got the correct register and correct fields. Ignore
            # the contents of the ones that haven't been explicitly set in
            # config, just make sure they are present.
            assert json_response["register_rows"][0]["index"] == "16"
            assert json_response["register_rows"][0]["type"] == "uint16"
            assert json_response["register_rows"][0]["value"] == "3124"
            assert "action" in json_response["register_rows"][0]
            assert "access" in json_response["register_rows"][0]
            assert "count_read" in json_response["register_rows"][0]
            assert "count_write" in json_response["register_rows"][0]

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_registers_json_invalid_params(self, client, simulator):
        """Test the /restapi/registers endpoint with invalid parameters."""
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/registers"
        data = {
            "submit": "Registers",
            "range_start": "invalid",
            "range_stop": 5,
        }

        async with client.post(url, json=data) as resp:
            # At the moment, errors are stored in the data. Only malformed
            # requests or bad endpoints will return a non-200 status code.
            assert resp.status == 200

            json_response = await resp.json()

            assert "error" in json_response
            assert json_response["error"] == "Invalid range parameters"

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_registers_json_non_existent_range(self, client, simulator):
        """Test the /restapi/registers endpoint with a non-existent range."""
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/registers"
        data = {
            "submit": "Registers",
            "range_start": 5,
            "range_stop": 7,
        }

        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["result"] == "ok"

            # The simulator should respond with all of the ranges, but the ones that
            # do not exist are marked as "invalid"
            assert len(json_response["register_rows"]) == 3

            assert json_response["register_rows"][0]["index"] == "5"
            assert json_response["register_rows"][0]["type"] == "bits"
            assert json_response["register_rows"][1]["index"] == "6"
            assert json_response["register_rows"][1]["type"] == "invalid"
            assert json_response["register_rows"][2]["index"] == "7"
            assert json_response["register_rows"][2]["type"] == "bits"

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_registers_json_set_value(self, client, simulator):
        """Test the /restapi/registers endpoint with a set value request."""
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/registers"
        data = {
            "submit": "Set",
            "register": 16,
            "value": 1234,
            # The range parameters are her edue to the API not being properly
            # formed (yet). They are equivalent of form fields that should not
            # be present in a smark json request.
            "range_start": 16,
            "range_stop": 16,
        }

        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()

            assert "result" in json_response
            assert json_response["result"] == "ok"

            # Check that the value was set correctly
            assert json_response["register_rows"][0]["index"] == "16"
            assert json_response["register_rows"][0]["value"] == "1234"

        # Double check that the value was set correctly, not just the response
        data2 = {
            "submit": "Registers",
            "range_start": 16,
            "range_stop": 16,
        }
        async with client.post(url, json=data2) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["result"] == "ok"

            assert json_response["register_rows"][0]["index"] == "16"
            assert json_response["register_rows"][0]["value"] == "1234"

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_registers_json_set_invalid_value(self, client, simulator):
        """Test the /restapi/registers endpoint with an invalid set value request."""
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/registers"
        data = {
            "submit": "Set",
            "register": 16,
            "value": "invalid",
        }

        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()

            assert "error" in json_response
            # Do not check for error content. It is currently
            # unhandled, so it is not guaranteed to be consistent.

    @pytest.mark.parametrize("response_type", [
        http_server.RESPONSE_NORMAL,
        http_server.RESPONSE_ERROR,
        http_server.RESPONSE_EMPTY,
        http_server.RESPONSE_JUNK
    ])
    @pytest.mark.parametrize("call", [
        ("split_delay", 1),
        ("response_cr_pct", 1),
        ("response_delay", 1),
        ("response_error", 1),
        ("response_junk_datalen", 1),
        ("response_clear_after", 1),
    ])
    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_calls_json_simulate(self, client, simulator, response_type, call):
        """
        Test the /restapi/calls endpoint to make sure simulations are set without errors.

        Some have extra parameters, others don't
        """
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/calls"

        # The default arguments which must be present in the request
        data = {
            "submit": "Simulate",
            "response_type": response_type,
            "response_split": "nomatter",
            "split_delay": 0,
            "response_cr": "nomatter",
            "response_cr_pct": 0,
            "response_delay": 0,
            "response_error": 0,
            "response_junk_datalen": 0,
            "response_clear_after": 0,
        }

        # Change the value of one call based on the parameter
        data[call[0]] = call[1]

        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["result"] == "ok"


    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_calls_json_simulate_reset_no_simulation(self, client, simulator):
        """
        Test the /restapi/calls endpoint with a reset request.

        Just make sure that there will be no error when resetting without triggering
        a simulation.
        """
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/calls"

        data = {
            "submit": "Reset",
        }

        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["result"] == "ok"

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_calls_json_simulate_reset_with_simulation(self, client, simulator):
        """Test the /restapi/calls endpoint with a reset request after a simulation."""
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/calls"

        data = {
            "submit": "Simulate",
            "response_type": http_server.RESPONSE_EMPTY,
            "response_split": "nomatter",
            "split_delay": 0,
            "response_cr": "nomatter",
            "response_cr_pct": 0,
            "response_delay": 100,
            "response_error": 0,
            "response_junk_datalen": 0,
            "response_clear_after": 0,
        }

        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["result"] == "ok"

        data = {
            "submit": "Reset",
        }

        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["result"] == "ok"

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_log_json_download(self, client, simulator):
        """
        Test the /restapi/log endpoint with a download request.

        This test is just a placeholder at the moment to make sure the endpoint
        is reachable. The actual functionality is not implemented.
        """
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/log"
        data = {
            "submit": "Download",
        }

        # The call is undefined. Just make sure it returns 200
        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["error"] == "log endpoint not implemented"

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_log_json_monitor(self, client, simulator):
        """
        Test the /restapi/log endpoint with a monitor request.

        This test is just a placeholder at the moment to make sure the endpoint
        is reachable. The actual functionality is not implemented.
        """
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/log"
        data = {
            "submit": "Monitor",
        }

        # The call is undefined. Just make sure it returns 200
        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["error"] == "log endpoint not implemented"

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_log_json_clear(self, client, simulator):
        """
        Test the /restapi/log endpoint with a clear request.

        This test is just a placeholder at the moment to make sure the endpoint
        is reachable. The actual functionality is not implemented.
        """
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/log"
        data = {
            "submit": "Clear",
        }

        # The call is undefined. Just make sure it returns 200
        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["error"] == "log endpoint not implemented"

    @pytest.mark.skip
    @pytest.mark.asyncio
    async def test_server_json_restart(self, client, simulator):
        """
        Test the /restapi/server endpoint with a restart request.

        This test is just a placeholder at the moment to make sure the endpoint
        is reachable. The actual functionality is not implemented.
        """
        url = f"http://{simulator.http_host}:{simulator.http_port}/restapi/server"
        data = {
            "submit": "Restart",
        }

        # The call is undefined. Just make sure it returns 200
        async with client.post(url, json=data) as resp:
            assert resp.status == 200

            json_response = await resp.json()
            assert json_response["error"] == "server endpoint not implemented"