zulip_botserver: Change style of type annotations to python3
This commit is contained in:
parent
641665c338
commit
2ba6f75fb3
|
@ -6,21 +6,19 @@ from zulip_botserver import server
|
||||||
|
|
||||||
class BotServerTestCase(TestCase):
|
class BotServerTestCase(TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
server.app.testing = True
|
server.app.testing = True
|
||||||
self.app = server.app.test_client()
|
self.app = server.app.test_client()
|
||||||
|
|
||||||
def assert_bot_server_response(self,
|
def assert_bot_server_response(self,
|
||||||
available_bots=None,
|
available_bots: Optional[List[str]]=None,
|
||||||
bots_config=None,
|
bots_config: Optional[Dict[str, Any]]=None,
|
||||||
bots_lib_module=None,
|
bots_lib_module: Optional[Dict[str, Any]]=None,
|
||||||
bot_handlers=None,
|
bot_handlers: Optional[Dict[str, Any]]=None,
|
||||||
payload_url="/bots/helloworld",
|
payload_url: str="/bots/helloworld",
|
||||||
message=dict(message={'key': "test message"}),
|
message: Optional[Dict[str, Any]]=dict(message={'key': "test message"}),
|
||||||
check_success=False,
|
check_success: bool=False,
|
||||||
):
|
) -> None:
|
||||||
# type: (Optional[List[str]], Optional[Dict[str, Any]], Optional[Dict[str, Any]], Optional[Dict[str, Any]], str, Dict[str, Dict[str, Any]], bool) -> None
|
|
||||||
if available_bots is not None:
|
if available_bots is not None:
|
||||||
server.available_bots = available_bots
|
server.available_bots = available_bots
|
||||||
server.bots_config = bots_config # type: ignore # monkey-patching
|
server.bots_config = bots_config # type: ignore # monkey-patching
|
||||||
|
|
|
@ -1,24 +1,20 @@
|
||||||
from __future__ import absolute_import
|
|
||||||
import mock
|
import mock
|
||||||
|
from typing import Any, Dict
|
||||||
import unittest
|
import unittest
|
||||||
from typing import Any
|
|
||||||
from .server_test_lib import BotServerTestCase
|
from .server_test_lib import BotServerTestCase
|
||||||
import six
|
import six
|
||||||
|
|
||||||
class BotServerTests(BotServerTestCase):
|
class BotServerTests(BotServerTestCase):
|
||||||
class MockMessageHandler(object):
|
class MockMessageHandler(object):
|
||||||
def handle_message(self, message, bot_handler):
|
def handle_message(self, message: Dict[str, str], bot_handler: Any) -> None:
|
||||||
# type: (Any, Any, Any) -> None
|
|
||||||
assert message == {'key': "test message"}
|
assert message == {'key': "test message"}
|
||||||
|
|
||||||
class MockLibModule(object):
|
class MockLibModule(object):
|
||||||
def handler_class(self):
|
def handler_class(self) -> Any:
|
||||||
# type: () -> Any
|
|
||||||
return BotServerTests.MockMessageHandler()
|
return BotServerTests.MockMessageHandler()
|
||||||
|
|
||||||
@mock.patch('zulip_botserver.server.ExternalBotHandler')
|
@mock.patch('zulip_botserver.server.ExternalBotHandler')
|
||||||
def test_successful_request(self, mock_ExternalBotHandler):
|
def test_successful_request(self, mock_ExternalBotHandler: mock.Mock) -> None:
|
||||||
# type: (mock.Mock) -> None
|
|
||||||
available_bots = ['helloworld']
|
available_bots = ['helloworld']
|
||||||
bots_config = {
|
bots_config = {
|
||||||
'helloworld': {
|
'helloworld': {
|
||||||
|
@ -31,16 +27,14 @@ class BotServerTests(BotServerTestCase):
|
||||||
bots_config=bots_config,
|
bots_config=bots_config,
|
||||||
check_success=True)
|
check_success=True)
|
||||||
|
|
||||||
def test_bot_module_not_exists(self):
|
def test_bot_module_not_exists(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
self.assert_bot_server_response(available_bots=[],
|
self.assert_bot_server_response(available_bots=[],
|
||||||
payload_url="/bots/not_supported_bot",
|
payload_url="/bots/not_supported_bot",
|
||||||
check_success=False)
|
check_success=False)
|
||||||
|
|
||||||
@mock.patch('logging.error')
|
@mock.patch('logging.error')
|
||||||
@mock.patch('zulip_bots.lib.StateHandler')
|
@mock.patch('zulip_bots.lib.StateHandler')
|
||||||
def test_wrong_bot_credentials(self, mock_StateHandler, mock_LoggingError):
|
def test_wrong_bot_credentials(self, mock_StateHandler: mock.Mock, mock_LoggingError: mock.Mock) -> None:
|
||||||
# type: (mock.Mock, mock.Mock) -> None
|
|
||||||
available_bots = ['nonexistent-bot']
|
available_bots = ['nonexistent-bot']
|
||||||
bots_config = {
|
bots_config = {
|
||||||
'nonexistent-bot': {
|
'nonexistent-bot': {
|
||||||
|
|
|
@ -5,7 +5,7 @@ import argparse
|
||||||
|
|
||||||
from flask import Flask, request
|
from flask import Flask, request
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
from typing import Any, Dict, Mapping, Union, List
|
from typing import Any, Dict, Mapping, Union, List, Optional
|
||||||
from werkzeug.exceptions import BadRequest
|
from werkzeug.exceptions import BadRequest
|
||||||
from six.moves.configparser import SafeConfigParser
|
from six.moves.configparser import SafeConfigParser
|
||||||
|
|
||||||
|
@ -18,8 +18,7 @@ available_bots = [] # type: List[str]
|
||||||
bots_lib_module = {} # type: Dict[str, Any]
|
bots_lib_module = {} # type: Dict[str, Any]
|
||||||
bot_handlers = {} # type: Dict[str, ExternalBotHandler]
|
bot_handlers = {} # type: Dict[str, ExternalBotHandler]
|
||||||
|
|
||||||
def read_config_file(config_file_path):
|
def read_config_file(config_file_path: str) -> None:
|
||||||
# type: (str) -> None
|
|
||||||
config_file_path = os.path.abspath(os.path.expanduser(config_file_path))
|
config_file_path = os.path.abspath(os.path.expanduser(config_file_path))
|
||||||
if not os.path.isfile(config_file_path):
|
if not os.path.isfile(config_file_path):
|
||||||
raise IOError("Could not read config file {}: File not found.".format(config_file_path))
|
raise IOError("Could not read config file {}: File not found.".format(config_file_path))
|
||||||
|
@ -33,8 +32,7 @@ def read_config_file(config_file_path):
|
||||||
"site": parser.get(section, 'site'),
|
"site": parser.get(section, 'site'),
|
||||||
}
|
}
|
||||||
|
|
||||||
def load_lib_modules():
|
def load_lib_modules() -> None:
|
||||||
# type: () -> None
|
|
||||||
for bot in available_bots:
|
for bot in available_bots:
|
||||||
try:
|
try:
|
||||||
module_name = 'zulip_bots.bots.{bot}.{bot}'.format(bot=bot)
|
module_name = 'zulip_bots.bots.{bot}.{bot}'.format(bot=bot)
|
||||||
|
@ -44,8 +42,7 @@ def load_lib_modules():
|
||||||
raise ImportError("\n Import Error: Bot \"{}\" doesn't exists. Please make sure you have set up the flaskbotrc "
|
raise ImportError("\n Import Error: Bot \"{}\" doesn't exists. Please make sure you have set up the flaskbotrc "
|
||||||
"file correctly.\n".format(bot))
|
"file correctly.\n".format(bot))
|
||||||
|
|
||||||
def load_bot_handlers():
|
def load_bot_handlers() -> Optional[BadRequest]:
|
||||||
# type: () -> Any
|
|
||||||
for bot in available_bots:
|
for bot in available_bots:
|
||||||
client = Client(email=bots_config[bot]["email"],
|
client = Client(email=bots_config[bot]["email"],
|
||||||
api_key=bots_config[bot]["key"],
|
api_key=bots_config[bot]["key"],
|
||||||
|
@ -77,9 +74,9 @@ def load_bot_handlers():
|
||||||
except SystemExit:
|
except SystemExit:
|
||||||
return BadRequest("Cannot fetch user profile for bot {}, make sure you have set up the flaskbotrc "
|
return BadRequest("Cannot fetch user profile for bot {}, make sure you have set up the flaskbotrc "
|
||||||
"file correctly.".format(bot))
|
"file correctly.".format(bot))
|
||||||
|
return None
|
||||||
|
|
||||||
def get_bot_lib_module(bot):
|
def get_bot_lib_module(bot: str) -> Any:
|
||||||
# type: (str) -> Any
|
|
||||||
if bot in bots_lib_module.keys():
|
if bot in bots_lib_module.keys():
|
||||||
return bots_lib_module[bot]
|
return bots_lib_module[bot]
|
||||||
return None
|
return None
|
||||||
|
@ -87,8 +84,7 @@ def get_bot_lib_module(bot):
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
@app.route('/bots/<bot>', methods=['POST'])
|
@app.route('/bots/<bot>', methods=['POST'])
|
||||||
def handle_bot(bot):
|
def handle_bot(bot: str) -> Union[str, BadRequest]:
|
||||||
# type: (str) -> Union[str, BadRequest]
|
|
||||||
lib_module = get_bot_lib_module(bot)
|
lib_module = get_bot_lib_module(bot)
|
||||||
if lib_module is None:
|
if lib_module is None:
|
||||||
return BadRequest("Can't find the configuration or Bot Handler code for bot {}. "
|
return BadRequest("Can't find the configuration or Bot Handler code for bot {}. "
|
||||||
|
@ -101,8 +97,7 @@ def handle_bot(bot):
|
||||||
bot_handler=bot_handlers[bot])
|
bot_handler=bot_handlers[bot])
|
||||||
return json.dumps("")
|
return json.dumps("")
|
||||||
|
|
||||||
def parse_args():
|
def parse_args() -> argparse.Namespace:
|
||||||
# type: () -> argparse.Namespace
|
|
||||||
usage = '''
|
usage = '''
|
||||||
zulip-bot-server --config-file <path to flaskbotrc> --hostname <address> --port <port>
|
zulip-bot-server --config-file <path to flaskbotrc> --hostname <address> --port <port>
|
||||||
Example: zulip-bot-server --config-file ~/flaskbotrc
|
Example: zulip-bot-server --config-file ~/flaskbotrc
|
||||||
|
@ -133,8 +128,7 @@ def parse_args():
|
||||||
return parser.parse_args()
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main() -> None:
|
||||||
# type: () -> None
|
|
||||||
options = parse_args()
|
options = parse_args()
|
||||||
read_config_file(options.config_file)
|
read_config_file(options.config_file)
|
||||||
global available_bots
|
global available_bots
|
||||||
|
|
Loading…
Reference in a new issue