matlab-proxy 0.15.0__py3-none-any.whl → 0.16.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of matlab-proxy might be problematic. Click here for more details.

Files changed (41) hide show
  1. matlab_proxy/app.py +13 -7
  2. matlab_proxy/app_state.py +9 -6
  3. matlab_proxy/constants.py +1 -0
  4. matlab_proxy/gui/asset-manifest.json +3 -3
  5. matlab_proxy/gui/index.html +1 -1
  6. matlab_proxy/gui/static/js/{main.14aa7840.js → main.522d83ba.js} +3 -3
  7. matlab_proxy/gui/static/js/main.522d83ba.js.map +1 -0
  8. matlab_proxy/settings.py +7 -4
  9. matlab_proxy/util/__init__.py +8 -1
  10. matlab_proxy/util/mwi/token_auth.py +19 -5
  11. {matlab_proxy-0.15.0.dist-info → matlab_proxy-0.16.0.dist-info}/METADATA +1 -1
  12. {matlab_proxy-0.15.0.dist-info → matlab_proxy-0.16.0.dist-info}/RECORD +40 -20
  13. tests/integration/integration_tests_with_license/test_http_end_points.py +4 -4
  14. tests/integration/integration_tests_without_license/conftest.py +4 -3
  15. tests/integration/integration_tests_without_license/test_matlab_is_down_if_unlicensed.py +3 -0
  16. tests/unit/__init__.py +1 -0
  17. tests/unit/conftest.py +67 -0
  18. tests/unit/test_app.py +1113 -0
  19. tests/unit/test_app_state.py +586 -0
  20. tests/unit/test_constants.py +6 -0
  21. tests/unit/test_ddux.py +22 -0
  22. tests/unit/test_devel.py +246 -0
  23. tests/unit/test_non_dev_mode.py +169 -0
  24. tests/unit/test_settings.py +460 -0
  25. tests/unit/util/__init__.py +3 -0
  26. tests/unit/util/mwi/__init__.py +1 -0
  27. tests/unit/util/mwi/embedded_connector/__init__.py +1 -0
  28. tests/unit/util/mwi/embedded_connector/test_helpers.py +29 -0
  29. tests/unit/util/mwi/embedded_connector/test_request.py +64 -0
  30. tests/unit/util/mwi/test_custom_http_headers.py +281 -0
  31. tests/unit/util/mwi/test_logger.py +49 -0
  32. tests/unit/util/mwi/test_token_auth.py +303 -0
  33. tests/unit/util/mwi/test_validators.py +331 -0
  34. tests/unit/util/test_mw.py +550 -0
  35. tests/unit/util/test_util.py +135 -0
  36. matlab_proxy/gui/static/js/main.14aa7840.js.map +0 -1
  37. /matlab_proxy/gui/static/js/{main.14aa7840.js.LICENSE.txt → main.522d83ba.js.LICENSE.txt} +0 -0
  38. {matlab_proxy-0.15.0.dist-info → matlab_proxy-0.16.0.dist-info}/LICENSE.md +0 -0
  39. {matlab_proxy-0.15.0.dist-info → matlab_proxy-0.16.0.dist-info}/WHEEL +0 -0
  40. {matlab_proxy-0.15.0.dist-info → matlab_proxy-0.16.0.dist-info}/entry_points.txt +0 -0
  41. {matlab_proxy-0.15.0.dist-info → matlab_proxy-0.16.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,460 @@
1
+ # Copyright 2020-2024 The MathWorks, Inc.
2
+
3
+ import os
4
+ import ssl
5
+ import time
6
+ import tempfile
7
+
8
+ import matlab_proxy
9
+ import matlab_proxy.settings as settings
10
+ from matlab_proxy.constants import VERSION_INFO_FILE_NAME, DEFAULT_PROCESS_START_TIMEOUT
11
+ from pathlib import Path
12
+ import pytest
13
+ from matlab_proxy.util.mwi import environment_variables as mwi_env
14
+ from matlab_proxy.util.mwi.exceptions import MatlabInstallError
15
+
16
+ """This file tests methods defined in settings.py file
17
+ """
18
+
19
+
20
+ def version_info_file_content(matlab_version):
21
+ """Returns contents of VersionInfo.xml file for a specific matlab_version
22
+
23
+ Args:
24
+ matlab_version (str): MATLAB Version
25
+
26
+ Returns:
27
+ str: Contents of VersionInfo.xml file for a specific matlab version
28
+ """
29
+
30
+ """
31
+ Returns the contents of a valid VersionInfo.xml file
32
+ """
33
+ return f"""<!-- Version information for MathWorks R2020b Release -->
34
+ <MathWorks_version_info>
35
+ <version>9.9.0.1524771</version>
36
+ <release>{matlab_version}</release>
37
+ <description>Update 2</description>
38
+ <date>Nov 03 2020</date>
39
+ <checksum>2207788044</checksum>
40
+ </MathWorks_version_info>
41
+ """
42
+
43
+
44
+ @pytest.fixture(name="fake_matlab_empty_root_path")
45
+ def fake_matlab_empty_root_path_fixture(tmp_path):
46
+ empty_matlab_root = tmp_path / "R2020b"
47
+ os.makedirs(empty_matlab_root, exist_ok=True)
48
+ return empty_matlab_root
49
+
50
+
51
+ @pytest.fixture(name="fake_matlab_executable_path")
52
+ def fake_matlab_executable_path_fixture(fake_matlab_empty_root_path):
53
+ matlab_executable_path = fake_matlab_empty_root_path / "bin" / "matlab"
54
+ os.makedirs(matlab_executable_path, exist_ok=True)
55
+
56
+ return matlab_executable_path
57
+
58
+
59
+ def create_file(file_path, file_content):
60
+ with open(file_path, "w") as f:
61
+ f.write(file_content)
62
+
63
+
64
+ @pytest.fixture(name="fake_matlab_valid_version_info_file_path")
65
+ def fake_matlab_valid_version_info_file_path_fixture(fake_matlab_empty_root_path):
66
+ version_info_file_path = fake_matlab_empty_root_path / VERSION_INFO_FILE_NAME
67
+ create_file(version_info_file_path, version_info_file_content("R2020b"))
68
+
69
+ return version_info_file_path
70
+
71
+
72
+ @pytest.fixture(name="fake_matlab_root_path")
73
+ def fake_matlab_root_path_fixture(
74
+ fake_matlab_executable_path, fake_matlab_valid_version_info_file_path
75
+ ):
76
+ """Pytest fixture to create a fake matlab installation path.
77
+
78
+ Args:
79
+ fake_matlab_executable_path (Pytest fixture): Pytest fixture which returns path to a fake matlab executable
80
+ fake_matlab_valid_version_info_file_path (Pytest fixture): Pytest fixture which returns path of a VersionInfo.xml file for a fake matlab
81
+
82
+ Returns:
83
+ pathlib.Path: Path to a fake matlab root
84
+ """
85
+
86
+ return fake_matlab_executable_path.parent.parent
87
+
88
+
89
+ @pytest.fixture(name="mock_shutil_which_none")
90
+ def mock_shutil_which_none_fixture(mocker):
91
+ """Pytest fixture to mock shutil.which() method to return None
92
+
93
+ Args:
94
+ mocker : Built in pytest fixture
95
+ """
96
+ mocker.patch("shutil.which", return_value=None)
97
+
98
+
99
+ def test_get_matlab_root_path_none(mock_shutil_which_none):
100
+ """Test to check if settings.get_matlab_path() returns none when no matlab installation is present.
101
+
102
+ mock_shutil_which_none fixture mocks shutil.which() to return None
103
+
104
+ Args:
105
+ mock_shutil_which_none : Pytest fixture to mock shutil.which() method to return None.
106
+ """
107
+ with pytest.raises(MatlabInstallError) as e:
108
+ _ = settings.get_matlab_executable_and_root_path()
109
+
110
+
111
+ @pytest.fixture(name="mock_shutil_which")
112
+ def mock_shutil_which_fixture(mocker, fake_matlab_executable_path):
113
+ """Pytest fixture to mock shutil.which() method to return a temporary fake matlab path
114
+
115
+ Args:
116
+ mocker : Built in pytest fixture
117
+ fake_matlab_executable_path : Pytest fixture which returns path to fake matlab executable file
118
+ """
119
+ mocker.patch("shutil.which", return_value=fake_matlab_executable_path)
120
+
121
+
122
+ @pytest.fixture(name="non_existent_path")
123
+ def non_existent_path_fixture(tmp_path):
124
+ # Build path to a non existent folder
125
+ random_folder = tmp_path / f'{str(time.time()).replace(".", "")}'
126
+ non_existent_path = Path(tmp_path) / random_folder
127
+
128
+ return non_existent_path
129
+
130
+
131
+ def test_get_matlab_root_path(fake_matlab_root_path, mock_shutil_which):
132
+ """Test to check if a valid matlab path is returned
133
+
134
+
135
+ mock_shutil_which fixture mocks shutil.which() method to return a temporary path.
136
+
137
+ Args:
138
+ fake_matlab_executable_path : Pytest fixture which returns a path to fake matlab executable
139
+ mock_shutil_which : Pytest fixture to mock shutil.which() method to return a fake matlab path
140
+ """
141
+ assert settings.get_matlab_executable_and_root_path()[1] == fake_matlab_root_path
142
+
143
+
144
+ def test_get_matlab_root_path_invalid_custom_matlab_root(
145
+ monkeypatch, non_existent_path
146
+ ):
147
+ # Monkeypatch the env var
148
+ monkeypatch.setenv(
149
+ mwi_env.get_env_name_custom_matlab_root(), str(non_existent_path)
150
+ )
151
+
152
+ # Test for appropriate error
153
+ with pytest.raises(MatlabInstallError) as e:
154
+ _ = settings.get_matlab_executable_and_root_path()
155
+
156
+
157
+ def test_get_matlab_version_none():
158
+ """Test to check settings.get_matlab_version() returns None when no valid matlab path is provided."""
159
+ assert settings.get_matlab_version(None) is None
160
+
161
+
162
+ def test_get_matlab_version(fake_matlab_root_path, mock_shutil_which):
163
+ """Test if a matlab version is returned when from a Version.xml file.
164
+
165
+ mock_shutil_which fixture will mock the settings.get_matlab_path() to return a fake matlab path
166
+ which containing a valid VersionInfo.xml file. settings.get_matlab_version() will extract the matlab version
167
+ from this file
168
+
169
+ Args:
170
+ mock_shutil_which : Pytest fixture to mock shutil.which() method.
171
+ """
172
+ (
173
+ matlab_executable_path,
174
+ matlab_root_path,
175
+ ) = settings.get_matlab_executable_and_root_path()
176
+ settings.get_matlab_version(matlab_root_path) is not None
177
+
178
+
179
+ def test_get_matlab_version_invalid_custom_matlab_root(monkeypatch, non_existent_path):
180
+ # Monkeypatch the env var
181
+ monkeypatch.setenv(
182
+ mwi_env.get_env_name_custom_matlab_root(), str(non_existent_path)
183
+ )
184
+
185
+ assert settings.get_matlab_version(None) is None
186
+
187
+
188
+ def test_get_matlab_version_valid_custom_matlab_root(non_existent_path, monkeypatch):
189
+ """Test matlab version when a custom matlab root path is supplied
190
+
191
+ Args:
192
+ tmp_path : Built-in pytest fixture
193
+ monkeypatch : Built-in pytest fixture m
194
+ """
195
+ custom_matlab_root_path = non_existent_path
196
+ os.makedirs(custom_matlab_root_path, exist_ok=True)
197
+ matlab_version = "R2020b"
198
+
199
+ # Create a valid VersionInfo.xml file at custom matlab root
200
+ version_info_file_path = custom_matlab_root_path / VERSION_INFO_FILE_NAME
201
+ create_file(version_info_file_path, version_info_file_content(matlab_version))
202
+
203
+ # Monkeypatch the env var
204
+ monkeypatch.setenv(
205
+ mwi_env.get_env_name_custom_matlab_root(), str(custom_matlab_root_path)
206
+ )
207
+
208
+ actual_matlab_version = settings.get_matlab_version(custom_matlab_root_path)
209
+
210
+ assert actual_matlab_version == matlab_version
211
+
212
+
213
+ @pytest.mark.parametrize(
214
+ "matlab_version", ["R2020b", "R2021a"], ids=["R2020b", "R2021a"]
215
+ )
216
+ def test_settings_get_matlab_cmd_for_different_matlab_versions(
217
+ matlab_version, non_existent_path, monkeypatch
218
+ ):
219
+ """Test to check settings.get returns the correct matlab_cmd when MWI_CUSTOM_MATLAB_ROOT is set.
220
+
221
+ Args:
222
+ matlab_version (str): Matlab version
223
+ non_existent_path (Pytest fixture): Pytest fixture which returns a temporary non-existent path
224
+ monkeypatch (Builtin pytest fixture): Pytest fixture to monkeypatch environment variables.
225
+ """
226
+
227
+ # Create custom matlab root for specific matlab_version
228
+ custom_matlab_root_path = non_existent_path / matlab_version
229
+ os.makedirs(custom_matlab_root_path, exist_ok=True)
230
+
231
+ # Create a valid VersionInfo.xml file at custom matlab root
232
+ version_info_file_path = custom_matlab_root_path / VERSION_INFO_FILE_NAME
233
+ create_file(version_info_file_path, version_info_file_content(matlab_version))
234
+
235
+ monkeypatch.setenv(
236
+ mwi_env.get_env_name_custom_matlab_root(), str(custom_matlab_root_path)
237
+ )
238
+
239
+ # Assert matlab_version is in path to matlab_cmd
240
+ sett = settings.get(dev=False)
241
+ assert matlab_version in str(sett["matlab_cmd"][0])
242
+
243
+
244
+ def test_get_dev_true():
245
+ """Test to check settings returned by settings.get() method in dev mode."""
246
+ dev_mode_settings = settings.get(dev=True)
247
+
248
+ assert dev_mode_settings["matlab_cmd"][0] != "matlab"
249
+ assert dev_mode_settings["matlab_protocol"] == "http"
250
+
251
+
252
+ @pytest.fixture(name="patch_env_variables")
253
+ def patch_env_variables_fixture(monkeypatch):
254
+ """Pytest fixture to Monkeypatch MWI_APP_PORT, BASE_URL, APP_HOST AND MLM_LICENSE_FILE env variables
255
+
256
+
257
+ Args:
258
+ monkeypatch : Built-in pytest fixture
259
+ """
260
+ monkeypatch.setenv(mwi_env.get_env_name_base_url(), "/matlab")
261
+ monkeypatch.setenv(mwi_env.get_env_name_app_port(), "8900")
262
+ monkeypatch.setenv(mwi_env.get_env_name_app_host(), "localhost")
263
+ monkeypatch.setenv(mwi_env.get_env_name_network_license_manager(), "123@nlm")
264
+
265
+
266
+ def test_get_dev_false(patch_env_variables, mock_shutil_which, fake_matlab_root_path):
267
+ """Test settings.get() method in Non Dev mode.
268
+
269
+ In Non dev mode, settings.get() expects MWI_APP_PORT, MWI_BASE_URL, APP_HOST AND MLM_LICENSE_FILE env variables
270
+ to be present. patch_env_variables monkeypatches them.
271
+
272
+ Args:
273
+ patch_env_variables : Pytest fixture which monkeypatches some env variables.
274
+ """
275
+ _settings = settings.get(dev=False)
276
+ assert "matlab" in str(_settings["matlab_cmd"][0])
277
+ assert os.path.isdir(_settings["matlab_path"])
278
+ assert _settings["matlab_protocol"] == "https"
279
+
280
+
281
+ def test_get_mw_context_tags(monkeypatch):
282
+ """Tests get_mw_context_tags() function to return appropriate MW_CONTEXT_TAGS"""
283
+
284
+ # Monkeypatch env var MW_CONTEXT_TAGS to check for if condition
285
+ dockerhub_mw_context_tags = "MATLAB:DOCKERHUB:V1"
286
+ monkeypatch.setenv("MW_CONTEXT_TAGS", dockerhub_mw_context_tags)
287
+
288
+ extension_name = matlab_proxy.get_default_config_name()
289
+
290
+ matlab_proxy_base_context_tags = matlab_proxy.get_mwi_ddux_value(extension_name)
291
+ expected_result = f"{dockerhub_mw_context_tags},{matlab_proxy_base_context_tags}"
292
+
293
+ actual_result = settings.get_mw_context_tags(extension_name)
294
+
295
+ assert expected_result == actual_result
296
+
297
+
298
+ @pytest.mark.parametrize(
299
+ "timeout_value",
300
+ [
301
+ (130, 130),
302
+ ("asdf", DEFAULT_PROCESS_START_TIMEOUT),
303
+ (120.5, DEFAULT_PROCESS_START_TIMEOUT),
304
+ (None, DEFAULT_PROCESS_START_TIMEOUT),
305
+ ],
306
+ ids=["Valid number", "Invalid number", "Valid decimal number", "No value supplied"],
307
+ )
308
+ def test_get_process_timeout(timeout_value, monkeypatch):
309
+ """Parameterized test to check settings.test_get_process_timeout returns the correct timeout value when MWI_PROCESS_STARTUP_TIMEOUT is set.
310
+
311
+ Args:
312
+ timeout (str): Timeout for processes launched by matlab-proxy
313
+ monkeypatch (Builtin pytest fixture): Pytest fixture to monkeypatch environment variables.
314
+ """
315
+ # Arrange
316
+ supplied_timeout, expected_timeout = timeout_value[0], timeout_value[1]
317
+
318
+ # pytest would throw warnings if None is supplied to monkeypatch
319
+ if supplied_timeout:
320
+ monkeypatch.setenv(
321
+ mwi_env.get_env_name_process_startup_timeout(), str(supplied_timeout)
322
+ )
323
+
324
+ # Act
325
+ actual_timeout = settings.get_process_startup_timeout()
326
+
327
+ # Assert
328
+ assert expected_timeout == actual_timeout
329
+
330
+
331
+ def test_get_mwi_config_folder_dev():
332
+ ## Arrange
333
+ expected_config_dir = Path(tempfile.gettempdir()) / "MWI" / "tests"
334
+
335
+ # Act
336
+ actual_config_dir = settings.get_mwi_config_folder(dev=True)
337
+
338
+ # Assert
339
+ assert expected_config_dir == actual_config_dir
340
+
341
+
342
+ @pytest.mark.parametrize(
343
+ "hostname, home, expected_mwi_config_dir",
344
+ [
345
+ (
346
+ "bob",
347
+ Path("/home/bob"),
348
+ Path("/home/bob") / ".matlab" / "MWI" / "hosts" / "bob",
349
+ ),
350
+ (
351
+ "bob",
352
+ Path("/home/CommonProject"),
353
+ Path("/home/CommonProject") / ".matlab" / "MWI" / "hosts" / "bob",
354
+ ),
355
+ (
356
+ None,
357
+ Path("/home/CommonProject"),
358
+ Path("/home/CommonProject") / ".matlab" / "MWI",
359
+ ),
360
+ ],
361
+ ids=[
362
+ "Single host machine with unique $HOME per host",
363
+ "Multi-host machine with common $HOME for multiple hosts",
364
+ "default directory when hostname is missing",
365
+ ],
366
+ )
367
+ def test_get_mwi_config_folder(mocker, hostname, home, expected_mwi_config_dir):
368
+ # Arrange
369
+ mocker.patch("matlab_proxy.settings.Path.home", return_value=home)
370
+ mocker.patch("matlab_proxy.settings.socket.gethostname", return_value=hostname)
371
+
372
+ # Act
373
+ actual_config_dir = settings.get_mwi_config_folder()
374
+
375
+ # Assert
376
+ assert expected_mwi_config_dir == actual_config_dir
377
+
378
+
379
+ def test_get_ssl_context_with_SSL_disabled(monkeypatch, tmpdir):
380
+ monkeypatch.setenv(mwi_env.get_env_name_enable_ssl(), "False")
381
+ mwi_certs_dir = Path(tmpdir)
382
+ ssl_context = settings._validate_ssl_files_and_get_ssl_context(mwi_certs_dir)
383
+ assert ssl_context is None
384
+
385
+
386
+ def test_get_ssl_context_with_SSL_enabled_auto_generated_certs(
387
+ monkeypatch, mocker, tmpdir
388
+ ):
389
+ monkeypatch.setenv(mwi_env.get_env_name_enable_ssl(), "True")
390
+ mocker.patch(
391
+ "matlab_proxy.settings.generate_new_self_signed_certs",
392
+ return_value=("cert_path", "key_path"),
393
+ )
394
+ mock_ssl_context = mocker.patch("ssl.create_default_context")
395
+ mock_context = mocker.Mock()
396
+ mock_ssl_context.return_value = mock_context
397
+ mock_context.load_cert_chain.side_effect = None
398
+ mwi_certs_dir = Path(tmpdir)
399
+
400
+ ssl_context = settings._validate_ssl_files_and_get_ssl_context(mwi_certs_dir)
401
+ assert ssl_context is not None
402
+
403
+
404
+ def test_get_ssl_context_with_invalid_self_signed_certs_returns_none(mocker, tmpdir):
405
+ mocker.patch(
406
+ "matlab_proxy.settings.generate_new_self_signed_certs",
407
+ return_value=("cert_path", "key_path"),
408
+ )
409
+ mock_ssl_context = mocker.patch("ssl.create_default_context")
410
+ mock_context = mocker.Mock()
411
+ mock_ssl_context.return_value = mock_context
412
+ exception_msg = "Invalid certificate!"
413
+ mock_context.load_cert_chain.side_effect = Exception(exception_msg)
414
+ mwi_certs_dir = Path(tmpdir)
415
+
416
+ assert settings._validate_ssl_files_and_get_ssl_context(mwi_certs_dir) is None
417
+
418
+
419
+ def test_get_ssl_context_with_valid_custom_ssl_files(monkeypatch, mocker, tmpdir):
420
+ # Sets up the SUT
421
+ monkeypatch.setenv(mwi_env.get_env_name_enable_ssl(), "True")
422
+ monkeypatch.setenv(mwi_env.get_env_name_ssl_cert_file(), "test/cert.pem")
423
+ monkeypatch.setenv(mwi_env.get_env_name_ssl_key_file(), "test/key.pem")
424
+ mocker.patch(
425
+ "matlab_proxy.settings.mwi.validators.validate_ssl_key_and_cert_file",
426
+ return_value=("test/cert.pem", "test/key.pem"),
427
+ )
428
+ new_cert_fx = mocker.patch("matlab_proxy.settings.generate_new_self_signed_certs")
429
+ mock_ssl_context = mocker.patch("ssl.create_default_context")
430
+ mock_context = mocker.Mock()
431
+ mock_ssl_context.return_value = mock_context
432
+ mock_context.load_cert_chain.side_effect = None
433
+ mwi_certs_dir = Path(tmpdir)
434
+
435
+ ssl_context = settings._validate_ssl_files_and_get_ssl_context(mwi_certs_dir)
436
+ # Checks that self-signed certificate generation is not happening when user supplies valid ssl files
437
+ new_cert_fx.assert_not_called()
438
+ assert ssl_context is not None
439
+
440
+
441
+ def test_get_ssl_context_with_invalid_custom_ssl_files_raises_exception(
442
+ monkeypatch, mocker, tmpdir
443
+ ):
444
+ # Sets up the SUT
445
+ monkeypatch.setenv(mwi_env.get_env_name_enable_ssl(), "True")
446
+ monkeypatch.setenv(mwi_env.get_env_name_ssl_cert_file(), "test/cert.pem")
447
+ monkeypatch.setenv(mwi_env.get_env_name_ssl_key_file(), "test/key.pem")
448
+ mocker.patch(
449
+ "matlab_proxy.settings.mwi.validators.validate_ssl_key_and_cert_file",
450
+ return_value=("test/cert.pem", "test/key.pem"),
451
+ )
452
+ mock_ssl_context = mocker.patch("ssl.create_default_context")
453
+ mock_context = mocker.Mock()
454
+ mock_ssl_context.return_value = mock_context
455
+ exception_msg = "Invalid certificate!"
456
+ mock_context.load_cert_chain.side_effect = Exception(exception_msg)
457
+ mwi_certs_dir = Path(tmpdir)
458
+
459
+ with pytest.raises(Exception, match=exception_msg):
460
+ settings._validate_ssl_files_and_get_ssl_context(mwi_certs_dir)
@@ -0,0 +1,3 @@
1
+ # Copyright 2022 The MathWorks, Inc.
2
+
3
+ from tests.unit.util.test_mw import MockResponse
@@ -0,0 +1 @@
1
+ # Copyright 2022 The MathWorks, Inc.
@@ -0,0 +1 @@
1
+ # Copyright 2022 The MathWorks, Inc.
@@ -0,0 +1,29 @@
1
+ # Copyright 2022 The MathWorks, Inc.
2
+
3
+ from matlab_proxy.util import mwi
4
+
5
+
6
+ def test_get_data_to_eval_mcode():
7
+ necessary_keys = ["uuid", "messages", "computeToken"]
8
+ mcode = "exit"
9
+ data = mwi.embedded_connector.helpers.get_data_to_eval_mcode(mcode)
10
+
11
+ assert set(necessary_keys).issubset(set(data.keys()))
12
+ assert data["messages"]["Eval"][0]["mcode"] == mcode
13
+
14
+
15
+ def test_get_data_to_feval_mcode():
16
+ necessary_keys = ["uuid", "messages", "computeToken"]
17
+ m_function = "round"
18
+ args = [3.135, 2]
19
+ nargout = 2
20
+ data = mwi.embedded_connector.helpers.get_data_to_feval_mcode(
21
+ m_function, *args, nargout=nargout
22
+ )
23
+
24
+ assert set(necessary_keys).issubset(set(data.keys()))
25
+ feval_data = data["messages"]["FEval"][0]
26
+
27
+ assert feval_data["function"] == m_function
28
+ assert feval_data["arguments"] == args
29
+ assert feval_data["nargout"] == nargout
@@ -0,0 +1,64 @@
1
+ # Copyright 2022-2023 The MathWorks, Inc.
2
+
3
+ import pytest
4
+ from matlab_proxy.util import mwi
5
+ from matlab_proxy.util.mwi.exceptions import EmbeddedConnectorError
6
+ from tests.unit.util import MockResponse
7
+
8
+
9
+ async def test_send_request_success(mocker):
10
+ """Test to check the happy path for send_request
11
+ Args:
12
+ mocker : Built in pytest fixture
13
+ """
14
+ # Arrange
15
+ json_data = {"hello": "world"}
16
+ payload = json_data
17
+ mock_resp = MockResponse(payload=payload, ok=True)
18
+ _ = mocker.patch("aiohttp.ClientSession.request", return_value=mock_resp)
19
+
20
+ # Act
21
+ res = await mwi.embedded_connector.send_request(
22
+ url="https://localhost:3000", data=json_data, method="GET"
23
+ )
24
+
25
+ # Assert
26
+ assert json_data["hello"] == res["hello"]
27
+
28
+
29
+ async def test_send_request_failure(mocker):
30
+ """Test to check if send_request fails when
31
+ 1) EC does not respond
32
+ 2) url or method is not supplied
33
+ Args:
34
+ mocker : Built in pytest fixture
35
+ """
36
+
37
+ # Arrange
38
+ json_data = {"hello": "world"}
39
+
40
+ payload = json_data
41
+ mock_resp = MockResponse(payload=payload, ok=False)
42
+ _ = mocker.patch("aiohttp.ClientSession.request", return_value=mock_resp)
43
+
44
+ # Doesnt have url or data or method
45
+ mock_resp = MockResponse(payload=payload, ok=False)
46
+
47
+ # Act
48
+
49
+ # Failed to communicate with EmbeddedConnector
50
+ with pytest.raises(EmbeddedConnectorError):
51
+ _ = await mwi.embedded_connector.send_request(
52
+ url="https://localhost:3000", method="GET", data=json_data
53
+ )
54
+
55
+ for key in ["url", "method"]:
56
+ options = {
57
+ "url": "https://localhost:3000",
58
+ "data": json_data,
59
+ "method": "GET",
60
+ }
61
+ options[key] = ""
62
+ # Assert
63
+ with pytest.raises(EmbeddedConnectorError):
64
+ _ = await mwi.embedded_connector.send_request(**options)