Skip to content

Commit 445bbaa

Browse files
committed
Use mw_environment_variables module to access environment variable names
1 parent 1bbb396 commit 445bbaa

13 files changed

+69
-44
lines changed

jupyter_matlab_proxy/__init__.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
# Copyright 2020-2021 The MathWorks, Inc.
22

33
import os
4+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
45

56

67
def _get_env(port, base_url):
78
return {
8-
"APP_PORT": str(port),
9-
"BASE_URL": f"{base_url}matlab",
10-
"APP_HOST": "127.0.0.1",
11-
"MHLM_CONTEXT": "MATLAB_JUPYTER",
9+
mw_env.get_env_name_app_port(): str(port),
10+
mw_env.get_env_name_base_url(): f"{base_url}matlab",
11+
mw_env.get_env_name_app_host(): "127.0.0.1",
12+
mw_env.get_env_name_mhlm_context(): "MATLAB_JUPYTER",
1213
}
1314

1415

jupyter_matlab_proxy/app.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from .app_state import AppState
1212
from .util import mw_logger
1313
from .util.exceptions import LicensingError
14+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
1415
import pkgutil
1516
import mimetypes
1617

@@ -154,7 +155,7 @@ async def termination_integration_delete(req):
154155
'with pytest.raises()', there by causing the test : test_termination_integration_delete()
155156
to fail. Inorder to avoid this, adding the below if condition to check to skip sys.exit(0) when testing
156157
"""
157-
if os.environ.get("TEST", "False").lower() != "true":
158+
if not mw_env.is_testing_mode_enabled():
158159
sys.exit(0)
159160

160161

@@ -360,9 +361,7 @@ def create_app():
360361
app = web.Application()
361362

362363
# Get application settings
363-
app["settings"] = settings.get(
364-
dev=(os.environ.get("DEV", "false").lower() == "true")
365-
)
364+
app["settings"] = settings.get(dev=(mw_env.is_development_mode_enabled()))
366365

367366
# TODO Validate any settings
368367

@@ -371,7 +370,7 @@ def create_app():
371370

372371
# In development mode, the node development server proxies requests to this
373372
# development server instead of serving the static files directly
374-
if os.environ.get("DEV", "false").lower() != "true":
373+
if not mw_env.is_development_mode_enabled():
375374
app["static_route_table"] = make_static_route_table(app)
376375
for key in app["static_route_table"].keys():
377376
app.router.add_route("GET", key, static_get)

jupyter_matlab_proxy/app_state.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Copyright 2020-2021 The MathWorks, Inc.
22

33
import asyncio
4+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
45
import xml.etree.ElementTree as ET
56
import os
67
import json
@@ -60,7 +61,6 @@ def __delete_cached_licensing_file(self):
6061
# The file being absent is acceptable.
6162
pass
6263

63-
6464
def __reset_and_delete_cached_licensing(self):
6565
logger.info(f"Resetting cached licensing information...")
6666
self.licensing = None
@@ -312,7 +312,10 @@ def reserve_matlab_port(self):
312312
# FIXME Because of https://github.com/http-party/node-http-proxy/issues/1342 the
313313
# node application in development mode always uses port 31515 to bypass the
314314
# reverse proxy. Once this is addressed, remove this special case.
315-
if os.getenv("DEV") == "true" and os.getenv("TEST", "false").lower() != "true":
315+
if (
316+
mw_env.is_development_mode_enabled()
317+
and not mw_env.is_testing_mode_enabled()
318+
):
316319
self.matlab_port = 31515
317320
else:
318321

@@ -399,7 +402,7 @@ async def start_matlab(self, restart=False):
399402
matlab_env["MW_LOGIN_DISPLAY_NAME"] = self.licensing["display_name"]
400403
matlab_env["MW_LOGIN_USER_ID"] = self.licensing["user_id"]
401404
matlab_env["MW_LOGIN_PROFILE_ID"] = self.licensing["profile_id"]
402-
if os.getenv("MHLM_CONTEXT") is None:
405+
if os.getenv(mw_env.get_env_name_mhlm_context()) is None:
403406
matlab_env["MHLM_CONTEXT"] = "MATLAB_JAVASCRIPT_DESKTOP"
404407

405408
elif self.licensing["type"] == "nlm":

jupyter_matlab_proxy/devel.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import asyncio, aiohttp
55
from aiohttp import web
66
import socket, time, os, sys
7+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
78

89
desktop_html = b"""
910
<h1>Fake MATLAB Web Desktop</h1>
@@ -69,7 +70,7 @@ async def fake_matlab_started(app):
6970

7071
# If "123@brokenhost" is specified as the MLM_LICENSE_FILE, exit to simulate an
7172
# error
72-
nlm = os.environ.get("MLM_LICENSE_FILE")
73+
nlm = os.environ.get(mw_env.get_env_name_network_license_manager())
7374
if nlm == "123@brokenhost":
7475
# TODO This should output the exact same text as MATLAB would in the same error
7576
# state

jupyter_matlab_proxy/mw_environment_variables.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# Copyright 2021 The MathWorks, Inc.
22
"""This file lists and exposes the environment variables which are used by the integration."""
33

4+
import os
5+
46

57
def get_env_name_network_license_manager():
68
"""Specifies the path to valid license file or address of a network license server"""
@@ -47,9 +49,29 @@ def get_env_name_app_host():
4749
return "APP_HOST"
4850

4951

52+
def get_env_name_mhlm_context():
53+
"""Specifies the context from which MHLM was initiated. Used by DDUX in MATLAB."""
54+
return "MHLM_CONTEXT"
55+
56+
5057
def get_env_name_testing():
58+
"""Set to true when we are running tests in development mode."""
5159
return "TEST"
5260

5361

5462
def get_env_name_development():
63+
"""Set to true when we are in development mode."""
5564
return "DEV"
65+
66+
67+
def is_development_mode_enabled():
68+
"""Returns true if the app is in development mode."""
69+
return os.getenv(get_env_name_development()).lower() == "true"
70+
71+
72+
def is_testing_mode_enabled():
73+
"""Returns true if the app is in testing mode."""
74+
return (
75+
is_development_mode_enabled()
76+
and os.getenv(get_env_name_testing()).lower() == "true"
77+
)

jupyter_matlab_proxy/settings.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import socket
99
import shutil
1010
from .util import custom_http_headers, validators
11+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
1112

1213

1314
def get_matlab_path():
@@ -57,13 +58,13 @@ def get_dev_settings():
5758
],
5859
"create_xvfb_cmd": create_xvfb_cmd,
5960
"matlab_ready_file": matlab_ready_file,
60-
"base_url": os.environ.get("BASE_URL", ""),
61-
"app_port": os.environ.get("APP_PORT", 8000),
62-
"host_interface": os.environ.get("APP_HOST", "127.0.0.1"),
61+
"base_url": os.environ.get(mw_env.get_env_name_base_url(), ""),
62+
"app_port": os.environ.get(mw_env.get_env_name_app_port(), 8000),
63+
"host_interface": os.environ.get(mw_env.get_env_name_app_host(), "127.0.0.1"),
6364
"mwapikey": str(uuid.uuid4()),
6465
"matlab_protocol": "http",
6566
"matlab_display": ":1",
66-
"nlm_conn_str": os.environ.get("MLM_LICENSE_FILE"),
67+
"nlm_conn_str": os.environ.get(mw_env.get_env_name_network_license_manager()),
6768
"matlab_config_file": matlab_temp_dir / "proxy_app_config.json",
6869
"ws_env": ws_env,
6970
"mwa_api_endpoint": f"https://login{ws_env_suffix}.mathworks.com/authenticationws/service/v4",
@@ -89,7 +90,7 @@ def get(dev=False):
8990

9091
# If running tests using Pytest, it will set environment variable TEST to true before running tests.
9192
# Will make test env specific changes before returning the settings.
92-
if os.environ.get("TEST", "False").lower() == "true":
93+
if mw_env.is_testing_mode_enabled():
9394

9495
# Set ready_delay value to 0 for faster fake MATLAB startup.
9596
ready_delay = ["--ready-delay", "0"]
@@ -127,13 +128,13 @@ def get(dev=False):
127128
],
128129
"create_xvfb_cmd": create_xvfb_cmd,
129130
"matlab_ready_file": Path(tempfile.gettempdir()) / "connector.securePort",
130-
"base_url": os.environ["BASE_URL"],
131-
"app_port": os.environ["APP_PORT"],
132-
"host_interface": os.environ.get("APP_HOST"),
131+
"base_url": os.environ[mw_env.get_env_name_base_url()],
132+
"app_port": os.environ[mw_env.get_env_name_app_port()],
133+
"host_interface": os.environ.get(mw_env.get_env_name_app_host()),
133134
"mwapikey": str(uuid.uuid4()),
134135
"matlab_protocol": "https",
135136
"nlm_conn_str": validators.validate_mlm_license_file(
136-
os.environ.get("MLM_LICENSE_FILE")
137+
os.environ.get(mw_env.get_env_name_network_license_manager())
137138
),
138139
"matlab_config_file": Path.home() / ".matlab" / "proxy_app_config.json",
139140
"ws_env": ws_env,

jupyter_matlab_proxy/util/custom_http_headers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import os, json, sys
44
from json.decoder import JSONDecodeError
55
from . import mw_logger
6+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
67

78
logger = mw_logger.get()
89

@@ -180,7 +181,7 @@ def __get_custom_header_env_var():
180181
Returns:
181182
String: Environment variable containing path to the file containing custom headers.
182183
"""
183-
return "CUSTOM_HTTP_HEADERS"
184+
return mw_env.get_env_name_custom_http_headers()
184185

185186

186187
def __get_exception_statement():

jupyter_matlab_proxy/util/mw_logger.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import logging
66
import os
7+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
78

89

910
def get(init=False):
@@ -67,8 +68,8 @@ def get_environment_variable_names():
6768
{tuple}: name of environment variable to control log level,
6869
name of environment variable to control logging to file
6970
"""
70-
__log_file_environment_variable_name = "LOG_FILE"
71-
__log_level_environment_variable_name = "LOG_LEVEL"
71+
__log_file_environment_variable_name = mw_env.get_env_name_log_file()
72+
__log_level_environment_variable_name = mw_env.get_env_name_logging_level()
7273
return __log_level_environment_variable_name, __log_file_environment_variable_name
7374

7475

tests/test_devel.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import pytest, asyncio, socket, os, tempfile, requests, pty, time, subprocess, sys
44
from pathlib import Path
5+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
56
from collections import namedtuple
67

78
"""
@@ -37,7 +38,7 @@ def valid_nlm_fixture(monkeypatch):
3738
monkeypatch : A built-in pytest fixture
3839
"""
3940

40-
monkeypatch.setenv("MLM_LICENSE_FILE", "abc@nlm")
41+
monkeypatch.setenv(mw_env.get_env_name_network_license_manager(), "abc@nlm")
4142

4243

4344
@pytest.fixture(name="invalid_nlm")
@@ -51,7 +52,7 @@ def invalid_nlm_fixture(monkeypatch):
5152
monkeypatch : A built-in pytest fixture
5253
"""
5354

54-
monkeypatch.setenv("MLM_LICENSE_FILE", "123@brokenhost")
55+
monkeypatch.setenv(mw_env.get_env_name_network_license_manager(), "123@brokenhost")
5556

5657

5758
@pytest.fixture(name="matlab_process_setup")

tests/test_non_dev_mode.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
# Copyright 2021 The MathWorks, Inc.
22

3-
import pytest, os, socket, subprocess, tempfile, uuid, shutil
3+
import pytest, os, shutil
44
from unittest.mock import patch
5-
from aiohttp import web
6-
from jupyter_matlab_proxy import app
75
from distutils.dir_util import copy_tree
86
from pathlib import Path
9-
from jupyter_matlab_proxy import settings
107
import jupyter_matlab_proxy
8+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
119
from tests.test_app import FakeServer
1210

1311
"""
@@ -24,7 +22,7 @@ def matlab_port_fixture(monkeypatch):
2422
Args:
2523
monkeypatch : A built-in pytest fixture
2624
"""
27-
monkeypatch.setenv("DEV", "false")
25+
monkeypatch.setenv(mw_env.get_env_name_development(), "false")
2826

2927

3028
@pytest.fixture(name="build_frontend")

tests/test_settings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Copyright 2021 The MathWorks, Inc.
22

33
import jupyter_matlab_proxy.settings as settings
4+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
45
import pytest
56
from pathlib import Path
67
import os
@@ -132,7 +133,7 @@ def patch_env_variables_fixture(monkeypatch):
132133
monkeypatch.setenv("BASE_URL", "localhost")
133134
monkeypatch.setenv("APP_PORT", "8900")
134135
monkeypatch.setenv("APP_HOST", "localhost")
135-
monkeypatch.setenv("MLM_LICENSE_FILE", "123@nlm")
136+
monkeypatch.setenv(mw_env.get_env_name_network_license_manager(), "123@nlm")
136137

137138

138139
def test_get_dev_false(patch_env_variables, mock_shutil_which):

tests/util/test_custom_headers.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from json.decoder import JSONDecodeError
44
import pytest, os, time, json, stat
55
from jupyter_matlab_proxy.util import custom_http_headers
6+
from jupyter_matlab_proxy import mw_environment_variables as mw_env
67
from pathlib import Path
78
from contextlib import nullcontext as does_not_raise
89

@@ -44,7 +45,7 @@ def monkeypatch_env_var_with_json_file_fixture(
4445
to non-existent file in a temporary directory.
4546
"""
4647
monkeypatch.setenv(
47-
custom_http_headers.__get_custom_header_env_var(),
48+
mw_env.get_env_name_custom_http_headers(),
4849
str(non_existent_temp_json_file),
4950
)
5051

@@ -186,7 +187,7 @@ def test_get_with_json_file_no_error(
186187
have a non-existent temporary json file.
187188
valid_json_content : Pytest fixture which returns valid json data as a string.
188189
"""
189-
tmp_file_path = os.getenv(custom_http_headers.__get_custom_header_env_var())
190+
tmp_file_path = os.getenv(mw_env.get_env_name_custom_http_headers())
190191

191192
with open(tmp_file_path, "w") as f:
192193
f.write(valid_json_content)
@@ -205,7 +206,7 @@ def test_get_with_json_file_raise_exception(
205206
have a non-existent temporary json file.
206207
invalid_json_content : Pytest fixture which returns invalid json data as a string.
207208
"""
208-
tmp_file_path = os.getenv(custom_http_headers.__get_custom_header_env_var())
209+
tmp_file_path = os.getenv(mw_env.get_env_name_custom_http_headers())
209210

210211
with open(tmp_file_path, "w") as f:
211212
f.write(invalid_json_content)
@@ -228,9 +229,7 @@ def monkeypatch_env_var_with_invalid_json_string_fixture(
228229
non_existent_temp_json_file: Pytest fixture which returns a string containing path
229230
to non-existent file in a temporary directory.
230231
"""
231-
monkeypatch.setenv(
232-
custom_http_headers.__get_custom_header_env_var(), invalid_json_content
233-
)
232+
monkeypatch.setenv(mw_env.get_env_name_custom_http_headers(), invalid_json_content)
234233

235234

236235
def test_get_with_invalid_json_string(
@@ -259,9 +258,7 @@ def monkeypatch_env_var_with_valid_json_string_fixture(monkeypatch, valid_json_c
259258
non_existent_temp_json_file: Pytest fixture which returns a string containing path
260259
to non-existent file in a temporary directory.
261260
"""
262-
monkeypatch.setenv(
263-
custom_http_headers.__get_custom_header_env_var(), valid_json_content
264-
)
261+
monkeypatch.setenv(mw_env.get_env_name_custom_http_headers(), valid_json_content)
265262

266263

267264
def test_get_with_valid_json_string(monkeypatch_env_var_with_valid_json_string):
@@ -272,5 +269,5 @@ def test_get_with_valid_json_string(monkeypatch_env_var_with_valid_json_string):
272269
monkeypatch_env_var_with_valid_json_string : Pytest fixture which monkeypatches the env variable returned by __get_custom_header_env_var() to
273270
contain valid JSON data as a string.
274271
"""
275-
headers = json.loads(os.getenv(custom_http_headers.__get_custom_header_env_var()))
272+
headers = json.loads(os.getenv(mw_env.get_env_name_custom_http_headers()))
276273
assert headers == custom_http_headers.get()

tests/util/test_mw_validators.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,3 @@ def test_get_with_environment_variables(monkeypatch):
3939
assert conn_str == str(path)
4040
finally:
4141
os.remove(path)
42-

0 commit comments

Comments
 (0)