Skip to content
Merged
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
17 changes: 17 additions & 0 deletions .github/workflows/ci-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,23 @@ jobs:
- name: Run lint verification
run: ./scripts/lint.sh

typecheck:
name: Typecheck
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set up Python ${{ env.LATEST_SUPPORTED_PY }}
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ env.LATEST_SUPPORTED_PY }}
- name: Run mypy verification
run: ./scripts/run_mypy.sh

unittest:
name: Unit tests
runs-on: ubuntu-22.04
Expand Down
34 changes: 0 additions & 34 deletions .github/workflows/pytype.yml

This file was deleted.

10 changes: 0 additions & 10 deletions __init__.py

This file was deleted.

4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,7 @@ filterwarnings = [
'ignore:"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead:DeprecationWarning',
"ignore:The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.:DeprecationWarning",
]

[tool.mypy]
files = "slack_discovery_sdk/"
warn_unused_ignores = true
4 changes: 4 additions & 0 deletions requirements/dev-tools.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@

# ruff
ruff==0.17.5

# mypy
# Note: mypy 2 requires Python >=3.9; the type check runs on the latest Python only.
mypy>=2.4.1,<3; python_version >= "3.9"
20 changes: 20 additions & 0 deletions scripts/install_and_run_tests.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/bin/bash
# all: ./scripts/install_and_run_tests.sh
# single: ./scripts/install_and_run_tests.sh tests/test_rate_limit_support.py

script_dir=$(dirname $0)
cd ${script_dir}/..

test_target="$1"

./scripts/install.sh
./scripts/format.sh --no-install
./scripts/lint.sh --no-install

# Run tests
if [[ $test_target != "" ]]; then
pytest -vv $test_target
else
pytest
./scripts/run_mypy.sh --no-install

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): mypy isn't installed on 3.7 and 3.8, so this fails with mypy: command not found there. Maybe skip it on older Pythons?

fi
10 changes: 10 additions & 0 deletions scripts/run_mypy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/bash
script_dir=$(dirname $0)
cd ${script_dir}/..

# Install dependencies unless --no-install is specified
if [[ "$1" != "--no-install" ]]; then
./scripts/install.sh
fi

mypy --config-file pyproject.toml
1 change: 0 additions & 1 deletion slack_discovery_sdk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# Copyright 2021, Slack Technologies, LLC. All rights reserved.
# pytype: skip-file

"""The Slack Web API allows you to build applications that interact with Slack.

Expand Down
61 changes: 30 additions & 31 deletions slack_discovery_sdk/base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@
from http.client import HTTPResponse
from logging import Logger
from ssl import SSLContext
from typing import Dict
from typing import Any, Dict
from typing import Optional
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen, OpenerDirector, ProxyHandler, HTTPSHandler

from .errors import DiscoveryRequestError, DiscoveryApiError # type:ignore
from .errors import DiscoveryRequestError, DiscoveryApiError
from .internal_utils import (
convert_bool_to_0_or_1,
get_user_agent,
_get_url,
_build_unexpected_body_error_message,
) # type:ignore
from .rate_limit_support import RateLimiter, calculate_random_jitter # type:ignore
from .response import DiscoveryResponse # type:ignore
from .proxy_support import load_http_proxy_from_env # type:ignore
)
from .rate_limit_support import RateLimiter, calculate_random_jitter
from .response import DiscoveryResponse
from .proxy_support import load_http_proxy_from_env


class BaseDiscoveryClient:
Expand Down Expand Up @@ -156,7 +156,7 @@ def fetch_next_page(
api_url: str,
headers: Dict[str, str],
params: Dict[str, str],
) -> Dict[str, any]: # type:ignore
) -> Dict[str, Any]:
"""This method is supposed to be used only for DiscoveryResponse pagination.

You can paginate using Python's for iterator as below:
Expand Down Expand Up @@ -196,7 +196,7 @@ def _urllib_api_call(
API response
"""
# True/False -> "1"/"0"
params = convert_bool_to_0_or_1(params)
form_params = convert_bool_to_0_or_1(params) or {}
request_headers = self._build_urllib_request_headers(
token=self.token if token is None else token,
additional_headers=additional_headers,
Expand All @@ -205,7 +205,7 @@ def _urllib_api_call(
http_method=http_method,
url=url,
headers=request_headers,
params=params,
params=form_params,
)
raw_body = response.get("body", "")
parsed_body: Optional[dict] = None
Expand All @@ -221,7 +221,7 @@ def _urllib_api_call(
http_method=http_method,
api_url=url,
request_headers=request_headers,
request_params=params,
request_params=form_params,
raw_body=raw_body,
body=parsed_body,
headers=dict(response["headers"]),
Expand All @@ -234,8 +234,8 @@ def _perform_urllib_http_request(
http_method: str = "POST",
url: str,
headers: Dict[str, str],
params: Dict[str, str],
) -> Dict[str, any]: # type:ignore
params: Dict[str, Any],
) -> Dict[str, Any]:
"""Performs an HTTP request and parses the response.

Args:
Expand Down Expand Up @@ -294,7 +294,7 @@ def _perform_urllib_http_request(
raise DiscoveryRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")

# NOTE: BAN-B310 is already checked above
resp: Optional[HTTPResponse] = None
resp: HTTPResponse
if opener:
resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310
else:
Expand All @@ -303,42 +303,41 @@ def _perform_urllib_http_request(
)

charset = resp.headers.get_content_charset() or "utf-8"
url_encoded_params: str = resp.read().decode(charset) # read the response body here
body = resp.read().decode(charset)
self._print_response_debug_log(
status_code=resp.code,
headers=resp.headers,
body=url_encoded_params,
status_code=resp.status,
headers=dict(resp.headers.items()),
body=body,
)
self.rate_limiter.append_api_call_result(
api_method=api_method,
is_success=True,
)
return {
"status": resp.code,
"status": resp.status,
"headers": resp.headers,
"body": url_encoded_params,
"body": body,
}
raise DiscoveryRequestError(f"Invalid URL detected: {url}")
except HTTPError as e:
self.rate_limiter.append_api_call_result(
api_method=api_method,
is_success=False,
)
resp = {"status": e.code, "headers": e.headers}
# read the response body here
error_resp: Dict[str, Any] = {"status": e.code, "headers": e.headers}
charset = e.headers.get_content_charset() or "utf-8"
url_encoded_params: str = e.read().decode(charset)
error_body = e.read().decode(charset)
if e.code == 429:
self._print_response_debug_log(
status_code=e.code,
headers=dict(e.headers.items()),
body=url_encoded_params,
body=error_body,
)
# for compatibility with aiohttp
resp["headers"]["Retry-After"] = resp["headers"]["retry-after"]
error_resp["headers"]["Retry-After"] = error_resp["headers"]["retry-after"]

if self.rate_limit_error_prevention_enabled is True:
sleep_seconds = int(resp["headers"]["retry-after"])
sleep_seconds = int(error_resp["headers"]["retry-after"])
log_message = f"Going to sleep for {sleep_seconds} seconds as this client got a rate limited error..."
self.logger.info(log_message)
time.sleep(sleep_seconds + calculate_random_jitter(factor=5.0))
Expand All @@ -351,8 +350,8 @@ def _perform_urllib_http_request(
params=params,
)

resp["body"] = url_encoded_params
return resp
error_resp["body"] = error_body
return error_resp

except Exception as err:
self.rate_limiter.append_api_call_result(
Expand Down Expand Up @@ -385,9 +384,9 @@ def convert_params(values: dict) -> dict:
def _print_response_debug_log(
self,
*,
status_code: Optional[int] = None,
headers: Optional[Dict[str, str]] = None,
body: Optional[str] = None,
status_code: int,
headers: Dict[str, str],
body: str,
):
if status_code >= 400:
self.logger.error(
Expand All @@ -398,7 +397,7 @@ def _print_response_debug_log(
f"Received the following response - status: {status_code}, headers: {dict(headers)}, body: {body}"
)

def _build_urllib_request_headers(self, *, token: str, additional_headers: dict) -> Dict[str, str]:
def _build_urllib_request_headers(self, *, token: Optional[str], additional_headers: dict) -> Dict[str, str]:
headers = {"Content-Type": "application/x-www-form-urlencoded"}
headers.update(self.headers)
if token:
Expand Down
6 changes: 3 additions & 3 deletions slack_discovery_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

from typing import Optional, Union

from .base_client import BaseDiscoveryClient # type:ignore
from .response import DiscoveryResponse # type:ignore
from .errors import DiscoveryRequestError # type:ignore
from .base_client import BaseDiscoveryClient
from .response import DiscoveryResponse
from .errors import DiscoveryRequestError


class DiscoveryClient(BaseDiscoveryClient):
Expand Down
4 changes: 2 additions & 2 deletions slack_discovery_sdk/examples/DLP_call_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

import logging
import os
from slack_discovery_sdk import DiscoveryClient # type: ignore
from slack_discovery_sdk import DiscoveryClient
from slack_sdk import WebClient

from utils import is_credit_card_number # type: ignore
from utils import is_credit_card_number # type: ignore[import-not-found]

logging.basicConfig(level=logging.DEBUG)

Expand Down
2 changes: 0 additions & 2 deletions slack_discovery_sdk/examples/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
# # Copyright 2021, Slack Technologies, LLC. All rights reserved.
# pytype: skip-file

"""The Slack Web API allows you to build applications that interact with Slack.

It lets you interact with Slack in more complex ways than the integrations we provide out of the box.
"""

from .. import slack_discovery_sdk # noqa
from . import utils # noqa
4 changes: 2 additions & 2 deletions slack_discovery_sdk/examples/audit_logs_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import logging
import os
import json
from slack_discovery_sdk import DiscoveryClient # type: ignore
from utils import export_json_to_file # type: ignore
from slack_discovery_sdk import DiscoveryClient
from utils import export_json_to_file # type: ignore[import-not-found]

from slack_sdk.audit_logs.v1.client import AuditLogsClient

Expand Down
2 changes: 1 addition & 1 deletion slack_discovery_sdk/examples/get_enterprise_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import logging
import os
from slack_discovery_sdk import DiscoveryClient # type: ignore
from slack_discovery_sdk import DiscoveryClient

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import logging
import os
import json
from slack_discovery_sdk import DiscoveryClient # type: ignore
from utils import export_json_to_file # type: ignore
from slack_discovery_sdk import DiscoveryClient
from utils import export_json_to_file # type: ignore[import-not-found]

logging.basicConfig(level=logging.DEBUG)

Expand Down
Loading
Loading