Skip to content

Commit

Permalink
Finalize the integration tests
Browse files Browse the repository at this point in the history
  • Loading branch information
seratch committed Apr 21, 2020
1 parent 57bd660 commit 78a96bc
Show file tree
Hide file tree
Showing 28 changed files with 81 additions and 217 deletions.
7 changes: 2 additions & 5 deletions integration_tests/rtm/test_issue_530.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@

import pytest

from integration_tests.env_variable_names import \
SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID
from integration_tests.helpers import async_test
from slack import RTMClient, WebClient
from slack import RTMClient


class TestRTMClient(unittest.TestCase):
Expand Down Expand Up @@ -53,4 +50,4 @@ async def test_issue_530_async(self):
# =============================================================================================== short test summary info ===============================================================================================
# FAILED integration_tests/rtm/test_issue_530.py::TestRTMClient::test_issue_530 - AssertionError: "'NoneType' object is not subscriptable" != "The server responded with: {'ok': False, 'error': 'invalid_auth'}"
# FAILED integration_tests/rtm/test_issue_530.py::TestRTMClient::test_issue_530_async - AssertionError: "'NoneType' object is not subscriptable" != "The server responded with: {'ok': False, 'error': 'invalid_auth'}"
# ====================================================================================== 2 failed, 1 skipped, 5 warnings in 1.54s =======================================================================================
# ====================================================================================== 2 failed, 1 skipped, 5 warnings in 1.54s =======================================================================================
2 changes: 1 addition & 1 deletion integration_tests/rtm/test_issue_558.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def tearDown(self):
# Reset the decorators by @RTMClient.run_on
RTMClient._callbacks = collections.defaultdict(list)

@pytest.mark.skip()
@pytest.mark.skip() # TODO: fix this
@async_test
async def test_issue_558(self):
channel_id = os.environ[SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID]
Expand Down
144 changes: 7 additions & 137 deletions integration_tests/rtm/test_issue_569.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,23 @@
import os
import threading
import time
import traceback
import unittest

import psutil
import pytest

from integration_tests.env_variable_names import SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
from integration_tests.env_variable_names import \
SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID
from integration_tests.helpers import async_test
from slack import RTMClient, WebClient


class TestRTMClient_Issue_569(unittest.TestCase):
"""Runs integration tests with real Slack API"""
"""Runs integration tests with real Slack API
https://github.com/slackapi/python-slackclient/issues/569
"""

def setUp(self):
if not hasattr(self, "logger"):
Expand Down Expand Up @@ -47,8 +50,7 @@ def tearDown(self):
if hasattr(self, "rtm_client") and not self.rtm_client._stopped:
self.rtm_client.stop()

# TODO: Fix this issue
@pytest.mark.skip("This needs to be fixed - https://github.com/slackapi/python-slackclient/issues/569")
@pytest.mark.skip() # TODO: Fix this issue
def test_cpu_usage(self):
self.rtm_client = RTMClient(
token=self.bot_token,
Expand Down Expand Up @@ -135,135 +137,3 @@ async def send_reply_async(**payload):
await asyncio.sleep(5)
self.assertLess(TestRTMClient_Issue_569.cpu_usage, 30, "Too high CPU usage detected")
self.assertEqual(self.call_count, 3, "The RTM handler failed")

# -----------------------
# Issue #631
# https://github.com/slackapi/python-slackclient/issues/631
# -----------------------

@pytest.mark.skip() # TODO: this issue needs to be fixed
def test_issue_631_sharing_event_loop(self):
self.success = None
self.text = "This message was sent to verify issue #631"

self.rtm_client = RTMClient(
token=self.bot_token,
run_async=False, # even though run_async=False, handlers for RTM events can be a coroutine
loop=asyncio.new_event_loop(), # TODO: remove this
)

# @RTMClient.run_on(event="message")
# def send_reply(**payload):
# self.logger.debug(payload)
# data = payload['data']
# web_client = payload['web_client']
# web_client._event_loop = self.loop
# # Maybe you will also need the following line uncommented
# # web_client.run_async = True
#
# if self.text in data['text']:
# channel_id = data['channel']
# thread_ts = data['ts']
# try:
# self.success = web_client.chat_postMessage(
# channel=channel_id,
# text="Thanks!",
# thread_ts=thread_ts
# )
# except Exception as e:
# # slack.rtm.client:client.py:446 When calling '#send_reply()'
# # in the 'test_rtm_client' module the following error was raised: This event loop is already running
# self.logger.error(traceback.format_exc())
# raise e

# Solution (1) for #631
@RTMClient.run_on(event="message")
# even though run_async=False, handlers for RTM events can be a coroutine
async def send_reply(**payload):
self.logger.debug(payload)
data = payload['data']
web_client = payload['web_client']

try:
if "text" in data and self.text in data["text"]:
channel_id = data['channel']
thread_ts = data['ts']
self.success = await web_client.chat_postMessage(
channel=channel_id,
text="Thanks!",
thread_ts=thread_ts
)
except Exception as e:
self.logger.error(traceback.format_exc())
raise e

def connect():
self.logger.debug("Starting RTM Client...")
self.rtm_client.start()

t = threading.Thread(target=connect)
t.setDaemon(True)
t.start()

try:
self.assertIsNone(self.success)
time.sleep(5)

self.web_client = WebClient(
token=self.bot_token,
run_async=False,
loop=asyncio.new_event_loop(), # TODO: this doesn't work without this
)
new_message = self.web_client.chat_postMessage(channel=self.channel_id, text=self.text)
self.assertFalse("error" in new_message)

time.sleep(5)
self.assertIsNotNone(self.success)
finally:
t.join(.3)

# Solution (2) for #631
@pytest.mark.skip("this is just for your reference")
@async_test
async def test_issue_631_sharing_event_loop_async(self):
self.success = None
self.text = "This message was sent to verify issue #631"

# To make run_async=True, the test method needs to be an async function + @async_test decorator
self.rtm_client = RTMClient(token=self.bot_token, run_async=True)
self.web_client = WebClient(token=self.bot_token, run_async=True)

@RTMClient.run_on(event="message")
async def send_reply(**payload):
self.logger.debug(payload)
data = payload['data']
web_client = payload['web_client']

try:
if "text" in data and self.text in data["text"]:
channel_id = data['channel']
thread_ts = data['ts']
self.success = await web_client.chat_postMessage(
channel=channel_id,
text="Thanks!",
thread_ts=thread_ts
)
except Exception as e:
self.logger.error(traceback.format_exc())
raise e

# intentionally not waiting here
self.rtm_client.start()

self.assertIsNone(self.success)
await asyncio.sleep(5)

self.web_client = WebClient(
token=self.bot_token,
run_async=True, # all need to be async here
)
new_message = await self.web_client.chat_postMessage(channel=self.channel_id, text=self.text)
self.assertFalse("error" in new_message)

await asyncio.sleep(5)
self.assertIsNotNone(self.success)
7 changes: 4 additions & 3 deletions integration_tests/rtm/test_issue_605.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

import pytest

from integration_tests.env_variable_names import SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
from integration_tests.env_variable_names import \
SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID
from slack import RTMClient, WebClient

Expand All @@ -29,7 +30,7 @@ def tearDown(self):
# Reset the decorators by @RTMClient.run_on
RTMClient._callbacks = collections.defaultdict(list)

@pytest.mark.skip()
@pytest.mark.skip() # TODO: Fix this issue
def test_issue_605(self):
self.text = "This message was sent to verify issue #605"
self.called = False
Expand Down Expand Up @@ -104,4 +105,4 @@ def connect():
# self._event_loop.add_signal_handler(s, self.stop)
# File "/path-to-python/asyncio/unix_events.py", line 97, in add_signal_handler
# raise RuntimeError(str(exc))
# RuntimeError: set_wakeup_fd only works in main thread
# RuntimeError: set_wakeup_fd only works in main thread
7 changes: 4 additions & 3 deletions integration_tests/rtm/test_issue_611.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

import pytest

from integration_tests.env_variable_names import SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
from integration_tests.env_variable_names import \
SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID
from integration_tests.helpers import async_test
from slack import RTMClient, WebClient
Expand All @@ -26,7 +27,7 @@ def tearDown(self):
# Reset the decorators by @RTMClient.run_on
RTMClient._callbacks = collections.defaultdict(list)

@pytest.mark.skip() # TODO: Fix this
@pytest.mark.skip() # TODO: Fix this
@async_test
async def test_issue_611(self):
channel_id = os.environ[SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID]
Expand All @@ -40,7 +41,7 @@ def process_messages(**payload):
return # skip

self.message_count += 1
raise Exception # This causes the termination of the process
raise Exception # This causes the termination of the process

def process_reactions(**payload):
self.logger.info(payload)
Expand Down
13 changes: 6 additions & 7 deletions integration_tests/rtm/test_issue_631.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,18 @@

import pytest

from integration_tests.env_variable_names import SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
from integration_tests.env_variable_names import \
SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID
from integration_tests.helpers import async_test
from slack import RTMClient, WebClient


class TestRTMClient_Issue_631(unittest.TestCase):
"""Runs integration tests with real Slack API"""
"""Runs integration tests with real Slack API
https://github.com/slackapi/python-slackclient/issues/631
"""

def setUp(self):
if not hasattr(self, "logger"):
Expand All @@ -31,11 +35,6 @@ def tearDown(self):
if hasattr(self, "rtm_client") and not self.rtm_client._stopped:
self.rtm_client.stop()

# -----------------------
# Issue #631
# https://github.com/slackapi/python-slackclient/issues/631
# -----------------------

@pytest.mark.skip() # TODO: this issue needs to be fixed
def test_issue_631_sharing_event_loop(self):
self.success = None
Expand Down
20 changes: 2 additions & 18 deletions integration_tests/rtm/test_rtm_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
import time
import unittest

import psutil

from integration_tests.env_variable_names import SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
from integration_tests.env_variable_names import \
SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \
SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID
from integration_tests.helpers import async_test
from slack import RTMClient, WebClient
Expand All @@ -23,21 +22,6 @@ def setUp(self):
self.channel_id = os.environ[SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID]
self.bot_token = os.environ[SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN]

if not hasattr(self, "cpu_monitor") or not TestRTMClient.cpu_monitor.is_alive():
def run_cpu_monitor(self):
self.logger.debug("Starting CPU monitor in another thread...")
TestRTMClient.cpu_usage = 0
while True:
p = psutil.Process(os.getpid())
current_cpu_usage: float = p.cpu_percent(interval=0.5)
self.logger.debug(current_cpu_usage)
if current_cpu_usage > TestRTMClient.cpu_usage:
TestRTMClient.cpu_usage = current_cpu_usage

TestRTMClient.cpu_monitor = threading.Thread(target=run_cpu_monitor, args=[self])
TestRTMClient.cpu_monitor.setDaemon(True)
TestRTMClient.cpu_monitor.start()

def tearDown(self):
# Reset the decorators by @RTMClient.run_on
RTMClient._callbacks = collections.defaultdict(list)
Expand Down
4 changes: 2 additions & 2 deletions integration_tests/samples/basic_usage/channels.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ------------------
# Only for running this script here
from os.path import dirname
import sys
import logging
import sys
from os.path import dirname

sys.path.insert(1, f"{dirname(__file__)}/../../..")
logging.basicConfig(level=logging.DEBUG)
Expand Down
4 changes: 2 additions & 2 deletions integration_tests/samples/basic_usage/emoji_reactions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ------------------
# Only for running this script here
from os.path import dirname
import sys
import logging
import sys
from os.path import dirname

sys.path.insert(1, f"{dirname(__file__)}/../../..")
logging.basicConfig(level=logging.DEBUG)
Expand Down
4 changes: 2 additions & 2 deletions integration_tests/samples/basic_usage/rate_limits.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ------------------
# Only for running this script here
from os.path import dirname
import sys
import logging
import sys
from os.path import dirname

sys.path.insert(1, f"{dirname(__file__)}/../../..")
logging.basicConfig(level=logging.DEBUG)
Expand Down
4 changes: 2 additions & 2 deletions integration_tests/samples/basic_usage/sending_a_message.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ------------------
# Only for running this script here
from os.path import dirname
import sys
import logging
import sys
from os.path import dirname

sys.path.insert(1, f"{dirname(__file__)}/../../..")
logging.basicConfig(level=logging.DEBUG)
Expand Down
4 changes: 2 additions & 2 deletions integration_tests/samples/basic_usage/uploading_files.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ------------------
# Only for running this script here
from os.path import dirname
import sys
import logging
import sys
from os.path import dirname

sys.path.insert(1, f"{dirname(__file__)}/../../..")
logging.basicConfig(level=logging.DEBUG)
Expand Down
4 changes: 2 additions & 2 deletions integration_tests/samples/basic_usage/users.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ------------------
# Only for running this script here
from os.path import dirname
import sys
import logging
import sys
from os.path import dirname

sys.path.insert(1, f"{dirname(__file__)}/../../..")
logging.basicConfig(level=logging.DEBUG)
Expand Down

0 comments on commit 78a96bc

Please sign in to comment.