Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions zulip/tests/test_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import os
import unittest
from unittest.mock import patch

import zulip


class TestConfigHelpers(unittest.TestCase):
def test_zulip_env_vars_are_present(self) -> None:
with patch.dict(os.environ, {}, clear=True):
self.assertFalse(zulip.zulip_env_vars_are_present())

with patch.dict(os.environ, {"ZULIP_EMAIL": "bot@example.com"}, clear=True):
self.assertFalse(zulip.zulip_env_vars_are_present())

with patch.dict(
os.environ,
{"ZULIP_EMAIL": "bot@example.com", "ZULIP_API_KEY": "secret_key"},
clear=True,
):
self.assertFalse(zulip.zulip_env_vars_are_present())

with patch.dict(
os.environ,
{
"ZULIP_EMAIL": "bot@example.com",
"ZULIP_API_KEY": "secret_key",
"ZULIP_SITE": "https://zulip.example.com",
},
clear=True,
):
self.assertTrue(zulip.zulip_env_vars_are_present())

def test_exit_gracefully_existing_file(self) -> None:
# Should return cleanly without exiting
zulip.exit_gracefully_if_zulip_config_is_missing(__file__)

def test_exit_gracefully_nonexistent_file(self) -> None:
with self.assertRaises(SystemExit) as cm:
zulip.exit_gracefully_if_zulip_config_is_missing("/nonexistent/path/to/zuliprc")
self.assertEqual(cm.exception.code, 1)

def test_exit_gracefully_with_env_vars(self) -> None:
with patch.dict(
os.environ,
{
"ZULIP_EMAIL": "bot@example.com",
"ZULIP_API_KEY": "secret_key",
"ZULIP_SITE": "https://zulip.example.com",
},
clear=True,
):
zulip.exit_gracefully_if_zulip_config_is_missing(None)

def test_exit_gracefully_default_config_exists(self) -> None:
with patch.dict(os.environ, {}, clear=True):
with patch("zulip.get_default_config_filename", return_value=__file__):
zulip.exit_gracefully_if_zulip_config_is_missing(None, allow_default_config=True)

def test_exit_gracefully_missing_all(self) -> None:
with patch.dict(os.environ, {}, clear=True):
with patch("zulip.get_default_config_filename", return_value="/nonexistent/zuliprc"):
with self.assertRaises(SystemExit) as cm:
zulip.exit_gracefully_if_zulip_config_is_missing(
None, allow_default_config=True
)
self.assertEqual(cm.exception.code, 1)

def test_exit_gracefully_disallow_default_config(self) -> None:
with patch.dict(os.environ, {}, clear=True):
with patch("zulip.get_default_config_filename", return_value=__file__):
with self.assertRaises(SystemExit) as cm:
zulip.exit_gracefully_if_zulip_config_is_missing(
None, allow_default_config=False
)
self.assertEqual(cm.exception.code, 1)
54 changes: 54 additions & 0 deletions zulip/zulip/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,60 @@ def get_default_config_filename() -> Optional[str]:
return config_file


def zulip_env_vars_are_present() -> bool:
"""Check if all necessary environment variables for Zulip API credentials are set."""
if os.environ.get("ZULIP_EMAIL") is None:
return False
if os.environ.get("ZULIP_API_KEY") is None:
return False
return os.environ.get("ZULIP_SITE") is not None


def exit_gracefully_if_zulip_config_is_missing(
config_file: Optional[str] = None, allow_default_config: bool = True
) -> None:
error_msg = None

if config_file is not None:
expanded_config_file = os.path.abspath(os.path.expanduser(config_file))
if os.path.exists(expanded_config_file):
return
else:
error_msg = f"ERROR: {config_file} does not exist."
elif zulip_env_vars_are_present():
return
elif allow_default_config:
env_config = os.environ.get("ZULIP_CONFIG")
if env_config is not None:
expanded_env = os.path.abspath(os.path.expanduser(env_config))
if os.path.exists(expanded_env):
return
else:
error_msg = f"ERROR: {env_config} does not exist."
else:
default_config = get_default_config_filename()
if default_config is not None and os.path.exists(default_config):
return
error_msg = "ERROR: You did not supply a Zulip config file."
else:
error_msg = "ERROR: You did not supply a Zulip config file."

if error_msg:
print("\n")
print(error_msg)
print(
"""
You may need to download a config file from the Zulip app, or
if you have already done that, you need to specify the file
location correctly on the command line.

If you don't want to use a config file, you must set
these env vars: ZULIP_EMAIL, ZULIP_API_KEY, ZULIP_SITE.
"""
)
sys.exit(1)


def validate_boolean_field(field: Optional[str]) -> Union[bool, None]:
if not isinstance(field, str):
return None
Expand Down
18 changes: 3 additions & 15 deletions zulip_bots/zulip_bots/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from typing_extensions import Protocol

import zulip
from zulip import Client, ZulipError


Expand All @@ -33,21 +34,8 @@ def get_bots_directory_path() -> str:


def zulip_env_vars_are_present() -> bool:
# We generally require a Zulip config file, but if
# the user supplies the correct environment vars, we
# waive the requirement. This can be helpful for
# containers like Heroku that prefer env vars to config
# files.
if os.environ.get("ZULIP_EMAIL") is None:
return False
if os.environ.get("ZULIP_API_KEY") is None:
return False
if os.environ.get("ZULIP_SITE") is None:
return False

# If none of the absolutely critical env vars are
# missing, we can proceed without a config file.
return True
# Retained for backwards compatibility; delegated to core zulip library.
return zulip.zulip_env_vars_are_present()


class RateLimit:
Expand Down
33 changes: 2 additions & 31 deletions zulip_bots/zulip_bots/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
import sys
from typing import Optional

import zulip
from zulip_bots import finder
from zulip_bots.lib import (
NoBotConfigError,
run_message_handler_for_bot,
zulip_env_vars_are_present,
)
from zulip_bots.provision import provision_bot

Expand Down Expand Up @@ -62,36 +62,7 @@ def parse_args() -> argparse.Namespace:


def exit_gracefully_if_zulip_config_is_missing(config_file: Optional[str]) -> None:
error_msg = None

if config_file:
if os.path.exists(config_file):
# We're good. (There may be problems with the config file,
# but we'll catch those later.
return
else:
error_msg = f"ERROR: {config_file} does not exist."

elif zulip_env_vars_are_present():
return
else:
error_msg = "ERROR: You did not supply a Zulip config file."

if error_msg:
print("\n")
print(error_msg)
print(
"""
You may need to download a config file from the Zulip app, or
if you have already done that, you need to specify the file
location correctly on the command line.

If you don't want to use a config file, you must set
these env vars: ZULIP_EMAIL, ZULIP_API_KEY, ZULIP_SITE.
"""
)

sys.exit(1)
zulip.exit_gracefully_if_zulip_config_is_missing(config_file, allow_default_config=False)


def exit_gracefully_if_bot_config_file_does_not_exist(bot_config_file: Optional[str]) -> None:
Expand Down
Loading