From 42157133da871518bf4b7eaf3f4efcf464c9ed27 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:47:49 -0500 Subject: [PATCH 1/8] build: move to pyproject.toml and drop python 3.6 Replace setup.py, setup.cfg, and pytest.ini with pyproject.toml, matching python-slack-sdk, bolt-python, and python-slack-hooks. The new floor is Python 3.7. A Python CI workflow runs the tests on 3.7 to 3.15 and PyPy, and tests that need live Discovery API tokens now skip without them. Co-Authored-By: Claude --- .github/dependabot.yml | 5 ++ .github/workflows/ci-build.yml | 91 +++++++++++++++++++++++++++++++ .github/workflows/flake8.yml | 3 +- .github/workflows/py_compile.yml | 39 ------------- .github/workflows/pytype.yml | 3 +- MANIFEST.in | 1 + README.md | 12 ++-- codecov.yml | 8 +++ pyproject.toml | 57 +++++++++++++++++++ pytest.ini | 10 ---- requirements/build.txt | 7 +++ requirements/testing.txt | 15 +++++ scripts/build.sh | 18 ------ scripts/build_pypi_package.sh | 14 +++++ scripts/deploy_to_test_pypi.sh | 8 +++ scripts/install.sh | 7 +++ scripts/run_all.sh | 18 ------ scripts/run_tests.sh | 15 +++++ scripts/set_env_vars.sh | 4 +- scripts/uninstall_all.sh | 9 +++ setup.cfg | 7 --- setup.py | 56 ------------------- tests/conftest.py | 14 +++++ tests/test_chat.py | 2 + tests/test_conversations.py | 1 + tests/test_draft.py | 2 + tests/test_enterprise.py | 2 + tests/test_file.py | 2 + tests/test_rate_limit_scenario.py | 1 + tests/test_users.py | 2 + 30 files changed, 274 insertions(+), 159 deletions(-) create mode 100644 .github/workflows/ci-build.yml delete mode 100644 .github/workflows/py_compile.yml create mode 100644 MANIFEST.in create mode 100644 codecov.yml create mode 100644 pyproject.toml delete mode 100644 pytest.ini create mode 100644 requirements/build.txt create mode 100644 requirements/testing.txt delete mode 100755 scripts/build.sh create mode 100755 scripts/build_pypi_package.sh create mode 100755 scripts/deploy_to_test_pypi.sh create mode 100755 scripts/install.sh delete mode 100755 scripts/run_all.sh create mode 100755 scripts/run_tests.sh create mode 100755 scripts/uninstall_all.sh delete mode 100644 setup.cfg delete mode 100644 setup.py create mode 100644 tests/conftest.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 8ac6b8c..9fce184 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,5 +1,10 @@ version: 2 updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 5 - package-ecosystem: "github-actions" directory: "/" schedule: diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml new file mode 100644 index 0000000..938ce38 --- /dev/null +++ b/.github/workflows/ci-build.yml @@ -0,0 +1,91 @@ +name: Python CI + +on: + push: + branches: + - main + pull_request: + schedule: + - cron: "0 0 * * *" + workflow_dispatch: + +env: + LATEST_SUPPORTED_PY: "3.15" + +jobs: + unittest: + name: Unit tests + runs-on: ubuntu-22.04 + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + python-version: + - "3.7" + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" + - "3.13" + - "3.14" + - "3.15" + - "pypy3.10" + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + pip install -U pip + pip install -e . + pip install -r requirements/testing.txt + - name: Run tests + run: | + pytest --junitxml=reports/test.xml + - name: Upload test results to Codecov + if: ${{ !cancelled() }} + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + directory: ./reports/ + fail_ci_if_error: true + flags: ${{ matrix.python-version }} + report_type: test_results + token: ${{ secrets.CODECOV_TOKEN }} + verbose: true + + codecov: + name: Code Coverage + runs-on: ubuntu-latest + timeout-minutes: 10 + 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: Install dependencies + run: | + pip install -U pip + pip install -e . + pip install -r requirements/testing.txt + - name: Run all tests for codecov + run: | + pytest --cov=./slack_discovery_sdk/ --cov-report=xml + - name: Upload coverage to Codecov + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + fail_ci_if_error: true + report_type: coverage + token: ${{ secrets.CODECOV_TOKEN }} + verbose: true diff --git a/.github/workflows/flake8.yml b/.github/workflows/flake8.yml index 3ca0954..8bf6459 100644 --- a/.github/workflows/flake8.yml +++ b/.github/workflows/flake8.yml @@ -26,8 +26,7 @@ jobs: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | - pip install -U pip - pip install -e ".[testing]" + ./scripts/install.sh # We manually upgrade it to make the builds stable pip install "flake8==6.1.0" - name: Run flake8 diff --git a/.github/workflows/py_compile.yml b/.github/workflows/py_compile.yml deleted file mode 100644 index 69e785a..0000000 --- a/.github/workflows/py_compile.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Sytanx check using py_compile - -on: - push: - branches: - - main - pull_request: -jobs: - build: - runs-on: ubuntu-22.04 - timeout-minutes: 5 - strategy: - matrix: - python-version: - - "3.7" - - "3.8" - - "3.9" - - "3.10" - - "3.11" - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - pip install -U pip - pip install -e ".[testing]" - - name: Run py_compile for main code - run: | - find slack_discovery_sdk -name '*.py' | xargs python -m py_compile - - name: Run py_compile for test code - run: | - find tests -name '*.py' | xargs python -m py_compile diff --git a/.github/workflows/pytype.yml b/.github/workflows/pytype.yml index 618bd8a..e5991a7 100644 --- a/.github/workflows/pytype.yml +++ b/.github/workflows/pytype.yml @@ -26,8 +26,7 @@ jobs: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | - pip install -U pip - pip install -e ".[testing]" + ./scripts/install.sh # As pytype can change its behavior in newer versions, we manually upgrade it pip install "pytype==2023.9.27" - name: Run pytype diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..bdd0a11 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1 @@ +include README.md LICENSE.md slack_discovery_sdk/py.typed diff --git a/README.md b/README.md index cb8a414..836665f 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ > ๐Ÿšจ Note: This SDK is only accessible to customer developers with access to the Discovery API (Enterprise accounts) or partners who have been onboarded to the Security and Compliance partner program. To learn more about the Discovery APIs, please [visit our help center](https://slack.com/help/articles/360002079527-A-guide-to-Slacks-Discovery-APIs). ๐Ÿšจ ## Prerequisites For Using the SDK -* Python version 3.6 or greater +* Python version 3.7 or greater * Latest version of pip * A token with discovery scopes (`discovery:read` and or `discovery:write`) > Note: Please see the [OAuth guide](https://api.slack.com/enterprise/discovery/oauth-guide) on how to get this token if you don't already have one. @@ -60,7 +60,7 @@ To view all of the methods offered by the SDK, please see the [client.py file](h In order to speed up the development process, we've provided you with a script called `set_env_vars.sh` in the scripts folder to automate a few things needed to run the SDK. The script accomplishes the following things using the following code: -* Prints your current Python version (**you will need Python version 3.6 or greater for this SDK**) +* Prints your current Python version (**you will need Python version 3.7 or greater for this SDK**) ```bash python3 --version ``` @@ -75,7 +75,7 @@ The script accomplishes the following things using the following code: ``` * Installs required packages and dependencies ```bash - pip install -e ".[testing]" + ./scripts/install.sh ``` ## ๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป Adding Env Variables to Setup Script ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป @@ -238,11 +238,11 @@ And then, setting the bot / user tokens in the env variables as below: ```bash # Setup your virtual environment -python --version # make sure if you're using Python 3.6+ +python --version # make sure if you're using Python 3.7+ python -m venv .venv source .venv/bin/activate pip install -U pip -pip install -e ".[testing]" +./scripts/install.sh # Set required env variables # 1. An admin user token with discovery:read, discovery:write @@ -257,6 +257,8 @@ export SLACK_DISCOVERY_SDK_TEST_TEAM_ID=T1234567890 export SLACK_DISCOVERY_SDK_TEST_CHANNEL_ID=C1234567890 pytest tests/ +# Without SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN, the tests that call the Discovery API are skipped + # You can check logs/pytest.log for trouble shooting ``` diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..5568e5e --- /dev/null +++ b/codecov.yml @@ -0,0 +1,8 @@ +coverage: + status: + project: + default: + threshold: 2.0% + patch: + default: + target: 50% diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a288ac6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,57 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "slack-discovery-sdk" +dynamic = ["version", "readme"] +description = "The Slack Discovery API SDK for Python" +license = { text = "MIT" } +authors = [{ name = "Slack Technologies, LLC", email = "opensource@slack.com" }] +requires-python = ">=3.7" +dependencies = [] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Topic :: Communications :: Chat", + "Topic :: Office/Business", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] + + +[project.urls] +Homepage = "https://github.com/slackapi/python-slack-discovery-sdk" +Documentation = "https://slack.com/help/articles/360002079527-A-guide-to-Slacks-Discovery-APIs" +Source = "https://github.com/slackapi/python-slack-discovery-sdk" + +[tool.setuptools.packages.find] +include = ["slack_discovery_sdk*"] + +[tool.setuptools.dynamic] +version = { attr = "slack_discovery_sdk.version.__version__" } +readme = { file = ["README.md"], content-type = "text/markdown" } + +[tool.pytest.ini_options] +testpaths = ["tests"] +log_file = "logs/pytest.log" +log_file_level = "DEBUG" +log_format = "%(asctime)s %(levelname)s %(message)s" +log_date_format = "%Y-%m-%d %H:%M:%S" +markers = ["live: calls the real Discovery API and needs the SLACK_DISCOVERY_SDK_TEST_* env variables"] +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", +] diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index db01ee0..0000000 --- a/pytest.ini +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -[pytest] -log_file = logs/pytest.log -log_file_level = DEBUG -log_format = %(asctime)s %(levelname)s %(message)s -log_date_format = %Y-%m-%d %H:%M:%S -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 \ No newline at end of file diff --git a/requirements/build.txt b/requirements/build.txt new file mode 100644 index 0000000..75e5969 --- /dev/null +++ b/requirements/build.txt @@ -0,0 +1,7 @@ +# pip install -r requirements/build.txt + +# twine +twine + +# build +build diff --git a/requirements/testing.txt b/requirements/testing.txt new file mode 100644 index 0000000..d8c232c --- /dev/null +++ b/requirements/testing.txt @@ -0,0 +1,15 @@ +# pip install -r requirements/testing.txt + +# slack_sdk +# Note: used by the live tests to post the messages and files that the Discovery API reads. +slack_sdk>=3.21.3,<4 + +# pytest +# Note: pytest 9 requires Python >=3.10; cap older interpreters below it. +pytest>=7.0.1,<9; python_version < "3.10" +pytest>=9.1.1,<10; python_version >= "3.10" + +# pytest-cov +# Note: pytest-cov 7.1+ requires Python >=3.9; cap older interpreters below it. +pytest-cov>=4,<7.1.0; python_version < "3.9" +pytest-cov>=7.1.0,<8; python_version >= "3.9" diff --git a/scripts/build.sh b/scripts/build.sh deleted file mode 100755 index b683a6a..0000000 --- a/scripts/build.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -script_dir=`dirname $0` -cd ${script_dir}/.. -version=`grep __version__ ./slack_discovery_sdk/version.py | awk -F'"' '{print $2}'` -while true; do - read -p "Do you wish to build a package for version ${version}? (y/N)" yn - case $yn in - [Yy]* ) make install; break;; - [Nn]* ) exit;; - * ) echo "Please answer yes or no.";; - esac -done - -pip install twine wheel && \ - rm -rf ./dist/ ./build/ *.egg-info/ && \ - python setup.py sdist bdist_wheel && \ - twine check dist/* diff --git a/scripts/build_pypi_package.sh b/scripts/build_pypi_package.sh new file mode 100755 index 0000000..7896218 --- /dev/null +++ b/scripts/build_pypi_package.sh @@ -0,0 +1,14 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +# Clean previous builds +rm -rf dist/ build/ slack_discovery_sdk.egg-info/ + +# Install build dependencies unless --no-install is specified +if [[ "$1" != "--no-install" ]]; then + pip install -r requirements/build.txt +fi + +# Build package +python -m build && twine check dist/* diff --git a/scripts/deploy_to_test_pypi.sh b/scripts/deploy_to_test_pypi.sh new file mode 100755 index 0000000..ac0c0e3 --- /dev/null +++ b/scripts/deploy_to_test_pypi.sh @@ -0,0 +1,8 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +./scripts/build_pypi_package.sh + +# Upload to test PyPI +twine upload --repository testpypi dist/* diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 0000000..bb50709 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,7 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +pip install -U pip +pip install -e . +pip install -r requirements/testing.txt diff --git a/scripts/run_all.sh b/scripts/run_all.sh deleted file mode 100755 index 09bbb56..0000000 --- a/scripts/run_all.sh +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -#!/bin/sh - -# run enterprise info -python3 slack_discovery_sdk/examples/get_enterprise_info.py - -# run DLP -python3 slack_discovery_sdk/examples/DLP_call_pattern.py - -# run eDiscovery without edits (commented out since we will be running pattern with edits) -# python3 slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py - -# run eDiscovery -python3 slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py - -# run auditLogs -python3 slack_discovery_sdk/examples/audit_logs_pattern.py \ No newline at end of file diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh new file mode 100755 index 0000000..12ea347 --- /dev/null +++ b/scripts/run_tests.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# all: ./scripts/run_tests.sh +# single: ./scripts/run_tests.sh tests/test_rate_limit_support.py + +script_dir=$(dirname $0) +cd ${script_dir}/.. + +test_target="$1" + +# Run tests +if [[ $test_target != "" ]]; then + pytest -vv $test_target +else + pytest +fi diff --git a/scripts/set_env_vars.sh b/scripts/set_env_vars.sh index 90e2b6c..d55f929 100755 --- a/scripts/set_env_vars.sh +++ b/scripts/set_env_vars.sh @@ -2,7 +2,7 @@ #!/bin/sh -# check to make sure Python version >= 3.6 is installed +# check to make sure Python version >= 3.7 is installed echo "Your current Python version is: " python3 --version @@ -19,7 +19,7 @@ echo "Sucessfully updated pip" # Installs required packages and dependencies echo "Installing required packages" -pip install -e ".[testing]" +./scripts/install.sh echo "Sucessfully installed required packages" ############# Needed to run SDK #################################### diff --git a/scripts/uninstall_all.sh b/scripts/uninstall_all.sh new file mode 100755 index 0000000..be0fea0 --- /dev/null +++ b/scripts/uninstall_all.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +pip uninstall -y slack-discovery-sdk + +PACKAGES=$(pip freeze | grep -v "^-e" | sed 's/@.*//' | sed 's/\=\=.*//') + +for package in $PACKAGES; do + pip uninstall -y $package +done diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 5cfff35..0000000 --- a/setup.cfg +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -[bdist_wheel] -universal = 1 - -[aliases] -test=pytest \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 79ccce4..0000000 --- a/setup.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -#!/usr/bin/env python -import os - -import setuptools - -here = os.path.abspath(os.path.dirname(__file__)) - -__version__ = None -exec(open(f"{here}/slack_discovery_sdk/version.py").read()) - -with open(f"{here}/README.md", "r") as fh: - long_description = fh.read() - -test_dependencies = [ - "slack_sdk>=3.21.3,<4", - "pytest>=6,<7", - "pytest-cov>=3,<4", - "black==22.8.0", # 22.10.0 or newer no longer exist for Python 3.6 -] - -setuptools.setup( - name="slack-discovery-sdk", - version=__version__, - author="Slack Technologies, LLC", - description="The Slack Discovery API SDK for Python", - long_description=long_description, - long_description_content_type="text/markdown", - packages=setuptools.find_packages( - exclude=[ - "tests", - "tests.*", - ] - ), - include_package_data=True, # MANIFEST.in - install_requires=[], - setup_requires=["pytest-runner==5.2"], - tests_require=test_dependencies, - test_suite="tests", - extras_require={ - # pip install -e ".[testing]" - "testing": test_dependencies, - }, - classifiers=[ - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: Implementation :: CPython", - "Operating System :: OS Independent", - ], - python_requires=">=3.6", -) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..7a247dc --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,14 @@ +import os + +import pytest + +from tests.env_variable_names import SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN + + +def pytest_collection_modifyitems(items): + if os.environ.get(SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN): + return + skip_live = pytest.mark.skip(reason=f"{SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN} is not set") + for item in items: + if "live" in item.keywords: + item.add_marker(skip_live) diff --git a/tests/test_chat.py b/tests/test_chat.py index 220bf8c..b698ae0 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_sdk import WebClient from slack_discovery_sdk import DiscoveryClient from .env_variable_names import ( @@ -11,6 +12,7 @@ ) +@pytest.mark.live class TestChat: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_conversations.py b/tests/test_conversations.py index 4eb0a05..dc4f3db 100644 --- a/tests/test_conversations.py +++ b/tests/test_conversations.py @@ -16,6 +16,7 @@ ) +@pytest.mark.live class TestConversations: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_draft.py b/tests/test_draft.py index c196ddf..ea038ff 100644 --- a/tests/test_draft.py +++ b/tests/test_draft.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_discovery_sdk import DiscoveryClient from tests.env_variable_names import ( SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN, @@ -9,6 +10,7 @@ ) +@pytest.mark.live class TestDraft: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_enterprise.py b/tests/test_enterprise.py index feeb2b2..5579d99 100644 --- a/tests/test_enterprise.py +++ b/tests/test_enterprise.py @@ -1,10 +1,12 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_discovery_sdk import DiscoveryClient from tests.env_variable_names import SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN +@pytest.mark.live class TestEnterprise: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_file.py b/tests/test_file.py index 2610fb8..ed9ca49 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_discovery_sdk import DiscoveryClient from slack_discovery_sdk.response import DiscoveryResponse from slack_sdk import WebClient @@ -12,6 +13,7 @@ ) +@pytest.mark.live class TestFile: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_rate_limit_scenario.py b/tests/test_rate_limit_scenario.py index a957ca1..97881bc 100644 --- a/tests/test_rate_limit_scenario.py +++ b/tests/test_rate_limit_scenario.py @@ -8,6 +8,7 @@ from concurrent.futures.thread import ThreadPoolExecutor +@pytest.mark.live class TestEnterprise: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_users.py b/tests/test_users.py index cfee420..9be52b7 100644 --- a/tests/test_users.py +++ b/tests/test_users.py @@ -1,10 +1,12 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_discovery_sdk import DiscoveryClient from tests.env_variable_names import SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN +@pytest.mark.live class TestUsers: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] From 674f1e2b5a874b3e8177fd2f1ec21e1acff474a1 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:48:13 -0500 Subject: [PATCH 2/8] build: replace black and flake8 with ruff Use the ruff config shared by python-slack-sdk, bolt-python, and python-slack-hooks, with format.sh and lint.sh scripts and a Lint CI job. This removes the .flake8 config and the flake8 workflow. Co-Authored-By: Claude --- .flake8 | 5 ----- .github/workflows/ci-build.yml | 17 +++++++++++++++++ .github/workflows/flake8.yml | 34 ---------------------------------- pyproject.toml | 23 +++++++++++++++++++++++ requirements/dev-tools.txt | 4 ++++ scripts/format.sh | 12 ++++++++++++ scripts/install.sh | 1 + scripts/lint.sh | 11 +++++++++++ scripts/run_tests.sh | 2 ++ 9 files changed, 70 insertions(+), 39 deletions(-) delete mode 100644 .flake8 delete mode 100644 .github/workflows/flake8.yml create mode 100644 requirements/dev-tools.txt create mode 100755 scripts/format.sh create mode 100755 scripts/lint.sh diff --git a/.flake8 b/.flake8 deleted file mode 100644 index b325547..0000000 --- a/.flake8 +++ /dev/null @@ -1,5 +0,0 @@ -[flake8] -max-line-length = 125 -# E401: We are fine with multiple imports in a line -# W503: This rule is not compatible with black (code formatter) -ignore = E401,W503 \ No newline at end of file diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 938ce38..c08febd 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -13,6 +13,23 @@ env: LATEST_SUPPORTED_PY: "3.15" jobs: + lint: + name: Lint + 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 lint verification + run: ./scripts/lint.sh + unittest: name: Unit tests runs-on: ubuntu-22.04 diff --git a/.github/workflows/flake8.yml b/.github/workflows/flake8.yml deleted file mode 100644 index 8bf6459..0000000 --- a/.github/workflows/flake8.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Lint validation using flake8 - -on: - push: - branches: - - main - pull_request: - -jobs: - build: - runs-on: ubuntu-latest - timeout-minutes: 5 - strategy: - matrix: - python-version: - - "3.9" - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - ./scripts/install.sh - # We manually upgrade it to make the builds stable - pip install "flake8==6.1.0" - - name: Run flake8 - run: | - flake8 slack_discovery_sdk/ diff --git a/pyproject.toml b/pyproject.toml index a288ac6..0d28b18 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,6 +44,29 @@ include = ["slack_discovery_sdk*"] version = { attr = "slack_discovery_sdk.version.__version__" } readme = { file = ["README.md"], content-type = "text/markdown" } +[tool.ruff] +line-length = 125 + +[tool.ruff.lint] +select = ["E", "W", "F", "D"] +ignore = [ + # missing-docstring: do not add docstrings where none exist + "D100", + "D101", + "D102", + "D103", + "D104", + "D105", + "D106", + "D107", +] + +[tool.ruff.lint.pydocstyle] +convention = "google" + +[tool.ruff.format] +docstring-code-format = true + [tool.pytest.ini_options] testpaths = ["tests"] log_file = "logs/pytest.log" diff --git a/requirements/dev-tools.txt b/requirements/dev-tools.txt new file mode 100644 index 0000000..c8d26c9 --- /dev/null +++ b/requirements/dev-tools.txt @@ -0,0 +1,4 @@ +# pip install -r requirements/dev-tools.txt + +# ruff +ruff==0.17.4 diff --git a/scripts/format.sh b/scripts/format.sh new file mode 100755 index 0000000..79ff8fc --- /dev/null +++ b/scripts/format.sh @@ -0,0 +1,12 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +# Install dependencies unless --no-install is specified +if [[ "$1" != "--no-install" ]]; then + pip install -U pip + pip install -r requirements/dev-tools.txt +fi + +ruff check --fix slack_discovery_sdk/ tests/ +ruff format slack_discovery_sdk/ tests/ diff --git a/scripts/install.sh b/scripts/install.sh index bb50709..94284f0 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -5,3 +5,4 @@ cd ${script_dir}/.. pip install -U pip pip install -e . pip install -r requirements/testing.txt +pip install -r requirements/dev-tools.txt diff --git a/scripts/lint.sh b/scripts/lint.sh new file mode 100755 index 0000000..dd6b35c --- /dev/null +++ b/scripts/lint.sh @@ -0,0 +1,11 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +# Install dependencies unless --no-install is specified +if [[ "$1" != "--no-install" ]]; then + pip install -U pip + pip install -r requirements/dev-tools.txt +fi + +ruff check slack_discovery_sdk/ tests/ && ruff format --check slack_discovery_sdk/ tests/ diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh index 12ea347..1df5ab5 100755 --- a/scripts/run_tests.sh +++ b/scripts/run_tests.sh @@ -7,6 +7,8 @@ cd ${script_dir}/.. test_target="$1" +./scripts/format.sh --no-install + # Run tests if [[ $test_target != "" ]]; then pytest -vv $test_target From 3d7526820ee8953576a3212f2214759630867adc Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:48:41 -0500 Subject: [PATCH 3/8] style: format with ruff Output of ./scripts/format.sh with no other changes: ruff format plus the safe ruff check fixes (one import per line, docstring blank lines, an unused import). Co-Authored-By: Claude --- slack_discovery_sdk/__init__.py | 4 +- slack_discovery_sdk/base_client.py | 70 ++++--------- slack_discovery_sdk/client.py | 99 +++++-------------- .../examples/DLP_call_pattern.py | 11 +-- slack_discovery_sdk/examples/__init__.py | 4 +- .../examples/audit_logs_pattern.py | 4 +- .../examples/get_enterprise_info.py | 3 +- .../examples/user_based_eDiscovery_pattern.py | 8 +- .../user_based_eDiscovery_with_edits.py | 12 +-- slack_discovery_sdk/examples/utils.py | 8 +- slack_discovery_sdk/internal_utils.py | 21 ++-- slack_discovery_sdk/proxy_support.py | 5 +- slack_discovery_sdk/rate_limit_support.py | 34 ++----- slack_discovery_sdk/response.py | 31 +++--- tests/test_chat.py | 12 +-- tests/test_conversations.py | 86 ++++------------ tests/test_draft.py | 4 +- tests/test_file.py | 35 ++----- tests/test_rate_limit_scenario.py | 8 +- tests/test_rate_limit_support.py | 9 +- 20 files changed, 148 insertions(+), 320 deletions(-) diff --git a/slack_discovery_sdk/__init__.py b/slack_discovery_sdk/__init__.py index 1ea2b8d..c7cc630 100644 --- a/slack_discovery_sdk/__init__.py +++ b/slack_discovery_sdk/__init__.py @@ -2,7 +2,9 @@ # pytype: skip-file """The Slack Web API allows you to build applications that interact with Slack -in more complex ways than the integrations we provide out of the box.""" +in more complex ways than the integrations we provide out of the box. +""" + from .client import DiscoveryClient from .oauth import DiscoveryOAuthApp diff --git a/slack_discovery_sdk/base_client.py b/slack_discovery_sdk/base_client.py index c8fef57..7073049 100644 --- a/slack_discovery_sdk/base_client.py +++ b/slack_discovery_sdk/base_client.py @@ -66,9 +66,7 @@ def __init__( self.ssl = ssl self.proxy = proxy self.headers = headers or {} - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.default_params = {} if team_id is not None: self.default_params["team_id"] = team_id @@ -100,6 +98,7 @@ def api_call( # skipcq: PYL-R1710 auth: Optional[dict] = None, ) -> DiscoveryResponse: """Create a request and execute the API call to Slack. + Args: api_method (str): The target Slack API method. e.g. 'discovery.enterprise.info' @@ -115,11 +114,11 @@ def api_call( # skipcq: PYL-R1710 from the response can be accessed like a dict. If the response included 'next_cursor' it can be iterated on to execute subsequent requests. + Raises: SlackApiError: The following Slack API call failed: 'discovery.enterprise.info'. """ - api_url = _get_url(self.base_url, api_method) headers = headers or {} headers.update(self.headers) @@ -130,14 +129,10 @@ def api_call( # skipcq: PYL-R1710 headers["Authorization"] = auth elif isinstance(auth, dict): client_id, client_secret = auth["client_id"], auth["client_secret"] - value = b64encode( - f"{client_id}:{client_secret}".encode("utf-8") - ).decode("ascii") + value = b64encode(f"{client_id}:{client_secret}".encode("utf-8")).decode("ascii") headers["Authorization"] = f"Basic {value}" else: - self.logger.warning( - f"As the auth: {auth}: {type(auth)} is unsupported, skipped" - ) + self.logger.warning(f"As the auth: {auth}: {type(auth)} is unsupported, skipped") token = self.token params = params or {} @@ -189,6 +184,7 @@ def _urllib_api_call( additional_headers: Dict[str, str], ) -> DiscoveryResponse: """Performs a Slack API request and returns the result. + Args: token: Slack API Token (either bot token or user token) url: Complete URL (e.g., https://slack.com/api/discovery.enterprise.info) @@ -197,7 +193,6 @@ def _urllib_api_call( Returns: API response """ - # True/False -> "1"/"0" params = convert_bool_to_0_or_1(params) request_headers = self._build_urllib_request_headers( @@ -240,15 +235,16 @@ def _perform_urllib_http_request( params: Dict[str, str], ) -> Dict[str, any]: # type:ignore """Performs an HTTP request and parses the response. + Args: url: Complete URL (e.g., https://slack.com/api/discovery.enterprise.info) args: args has "headers" and "params" "headers": Dict[str, str] "params": Dict[str, str], + Returns: dict {status: int, headers: Headers, body: str} """ - url_elements = url.split("/") if len(url_elements) >= 2: api_method = url_elements[-1].split("?")[0] # remove query string @@ -280,16 +276,10 @@ def _perform_urllib_http_request( headers=headers, ) elif http_method == "GET": - url = ( - f"{url}&{url_encoded_params}" - if "?" in url - else f"{url}?{url_encoded_params}" - ) + url = f"{url}&{url_encoded_params}" if "?" in url else f"{url}?{url_encoded_params}" req = Request(method="GET", url=url, headers=headers) else: - raise DiscoveryRequestError( - f"Unsupported HTTP method: {http_method}" - ) + raise DiscoveryRequestError(f"Unsupported HTTP method: {http_method}") opener: Optional[OpenerDirector] = None if self.proxy is not None: @@ -299,9 +289,7 @@ def _perform_urllib_http_request( HTTPSHandler(context=self.ssl), ) else: - raise DiscoveryRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise DiscoveryRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") # NOTE: BAN-B310 is already checked above resp: Optional[HTTPResponse] = None @@ -313,9 +301,7 @@ 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 + url_encoded_params: str = resp.read().decode(charset) # read the response body here self._print_response_debug_log( status_code=resp.code, headers=resp.headers, @@ -387,19 +373,11 @@ def _print_request_debug_log( def convert_params(values: dict) -> dict: if not values or not isinstance(values, dict): return {} - return { - k: ("(bytes)" if isinstance(v, bytes) else v) - for k, v in values.items() - } + return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()} - headers = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in headers.items() - } + headers = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()} self.logger.debug( - f"Sending a request - {http_method} {url}, " - f"params: {convert_params(params)}, " - f"headers: {headers}" + f"Sending a request - {http_method} {url}, params: {convert_params(params)}, headers: {headers}" ) def _print_response_debug_log( @@ -411,22 +389,14 @@ def _print_response_debug_log( ): if status_code >= 400: self.logger.error( - "Received the following response - " - f"status: {status_code}, " - f"headers: {dict(headers)}, " - f"body: {body}" + f"Received the following response - status: {status_code}, headers: {dict(headers)}, body: {body}" ) elif self.logger.level <= logging.DEBUG: self.logger.debug( - "Received the following response - " - f"status: {status_code}, " - f"headers: {dict(headers)}, " - f"body: {body}" + 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: str, additional_headers: dict) -> Dict[str, str]: headers = {"Content-Type": "application/x-www-form-urlencoded"} headers.update(self.headers) if token: @@ -442,9 +412,7 @@ def _do_stuff_for_rate_limit_error_prevention( ): if self.rate_limit_error_prevention_enabled is True: # Check the current traffic - sleep_duration: float = self.rate_limiter.calculate_sleep_duration( - api_method - ) + sleep_duration: float = self.rate_limiter.calculate_sleep_duration(api_method) if self.logger.level <= logging.DEBUG: report = self.rate_limiter.generate_metrics_report() self.logger.debug(f"""Rate limit metrics: {report}""") diff --git a/slack_discovery_sdk/client.py b/slack_discovery_sdk/client.py index ba746b9..444c435 100644 --- a/slack_discovery_sdk/client.py +++ b/slack_discovery_sdk/client.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. """A Python module for interacting with Slack's Discovery APIs.""" + from typing import Optional, Union from .base_client import BaseDiscoveryClient # type:ignore @@ -78,9 +79,7 @@ def discovery_enterprise_info( "include_deleted": include_deleted, } ) - return self.api_call( - "discovery.enterprise.info", http_method="GET", params=kwargs - ) + return self.api_call("discovery.enterprise.info", http_method="GET", params=kwargs) # ------------------------------------------------ # discovery.users @@ -157,9 +156,7 @@ def discovery_user_conversations( if offset is not None: kwargs.update({"offset": offset}) - return self.api_call( - "discovery.user.conversations", http_method="GET", params=kwargs - ) + return self.api_call("discovery.user.conversations", http_method="GET", params=kwargs) # ------------------------------------------------ # discovery.conversations @@ -182,9 +179,7 @@ def discovery_conversations_recent( Refer to https://api.slack.com/enterprise/discovery/methods#conversations_recent for more details. """ kwargs.update({"token": token, "team": team, "latest": latest, "limit": limit}) - return self.api_call( - "discovery.conversations.recent", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.recent", http_method="GET", params=kwargs) def discovery_conversations_list( self, @@ -217,9 +212,7 @@ def discovery_conversations_list( "limit": limit, } ) - return self.api_call( - "discovery.conversations.list", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.list", http_method="GET", params=kwargs) def discovery_conversations_history( self, @@ -240,9 +233,7 @@ def discovery_conversations_history( if isinstance(reactions, (int, str)): reactions = int(reactions) == 1 if not isinstance(reactions, bool): - raise DiscoveryRequestError( - f"Unexpected value type for reactions {type(reactions).__name__}" - ) + raise DiscoveryRequestError(f"Unexpected value type for reactions {type(reactions).__name__}") kwargs.update( { "token": token, @@ -254,9 +245,7 @@ def discovery_conversations_history( "limit": limit, } ) - return self.api_call( - "discovery.conversations.history", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.history", http_method="GET", params=kwargs) def discovery_conversations_edits( self, @@ -282,9 +271,7 @@ def discovery_conversations_edits( "limit": limit, } ) - return self.api_call( - "discovery.conversations.edits", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.edits", http_method="GET", params=kwargs) def discovery_conversations_info( self, @@ -306,9 +293,7 @@ def discovery_conversations_info( "offset": offset, } ) - return self.api_call( - "discovery.conversations.info", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.info", http_method="GET", params=kwargs) def discovery_conversations_members( self, @@ -334,9 +319,7 @@ def discovery_conversations_members( "limit": limit, } ) - return self.api_call( - "discovery.conversations.members", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.members", http_method="GET", params=kwargs) def discovery_conversations_renames( self, @@ -361,9 +344,7 @@ def discovery_conversations_renames( "private": private, } ) - return self.api_call( - "discovery.conversations.renames", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.renames", http_method="GET", params=kwargs) def discovery_conversations_reactions( self, @@ -389,9 +370,7 @@ def discovery_conversations_reactions( "limit": limit, } ) - return self.api_call( - "discovery.conversations.reactions", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.reactions", http_method="GET", params=kwargs) def discovery_conversations_search( self, @@ -422,9 +401,7 @@ def discovery_conversations_search( "offset": offset, } ) - return self.api_call( - "discovery.conversations.search", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.search", http_method="GET", params=kwargs) # ------------------------------------------------ # discovery.chat @@ -443,7 +420,6 @@ def discovery_chat_info( this method returns the current, edited (or deleted) message. Refer to https://api.slack.com/enterprise/discovery/methods#chat_info for more details. """ - kwargs.update( { "token": token, @@ -469,7 +445,6 @@ def discovery_chat_update( should be included in place of the message. Refer to https://api.slack.com/enterprise/discovery/methods#chat_update for more details. """ - kwargs.update( { "token": token, @@ -494,7 +469,6 @@ def discovery_chat_delete( """Deletes a message. This method purges the history, edits, and message from the Slack databases. Refer to https://api.slack.com/enterprise/discovery/methods#chat_delete for more details. """ - kwargs.update( { "token": token, @@ -518,7 +492,6 @@ def discovery_chat_tombstone( """Use this method to update and or obscure a message in the event that the message violated policy. Refer to https://api.slack.com/enterprise/discovery/methods#chat_tombstone for more details. """ - kwargs.update( { "token": token, @@ -528,9 +501,7 @@ def discovery_chat_tombstone( "content": content, } ) - return self.api_call( - "discovery.chat.tombstone", http_method="POST", params=kwargs - ) + return self.api_call("discovery.chat.tombstone", http_method="POST", params=kwargs) def discovery_chat_restore( self, @@ -544,7 +515,6 @@ def discovery_chat_restore( """Use this method to restore a tombstoned message to the client. Refer to https://api.slack.com/enterprise/discovery/methods#chat_restore for more details. """ - kwargs.update( { "token": token, @@ -553,9 +523,7 @@ def discovery_chat_restore( "team": team, } ) - return self.api_call( - "discovery.chat.restore", http_method="POST", params=kwargs - ) + return self.api_call("discovery.chat.restore", http_method="POST", params=kwargs) # ------------------------------------------------ # discovery.draft @@ -575,7 +543,6 @@ def discovery_drafts_list( """The discovery.drafts.list method returns a list of drafts created upon the specified team. Refer to https://api.slack.com/enterprise/discovery/methods#drafts_list for more details. """ - kwargs.update( { "token": token, @@ -604,7 +571,6 @@ def discovery_draft_info( """The discovery.draft.info endpoint provides information associated with a singular draft. Refer to https://api.slack.com/enterprise/discovery/methods#drafts_info for more details. """ - kwargs.update( { "token": token, @@ -636,7 +602,6 @@ def discovery_files_list( """This method returns files uploaded within a specified timeframe. Refer to https://api.slack.com/enterprise/discovery/methods#files_list for more details. """ - kwargs.update( { "token": token, @@ -648,13 +613,10 @@ def discovery_files_list( ) return self.api_call("discovery.files.list", http_method="GET", params=kwargs) - def discovery_file_info( - self, *, token: Optional[str] = None, file: str, **kwargs - ) -> DiscoveryResponse: + def discovery_file_info(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """All file comments are shown here. File comments are Slack's odd message type. Refer to https://api.slack.com/enterprise/discovery/methods#file_info for more details. """ - kwargs.update({"token": token, "file": file}) return self.api_call("discovery.file.info", http_method="GET", params=kwargs) @@ -671,17 +633,10 @@ def discovery_file_tombstone( because it will not be accessible after tombstoning. Refer to https://api.slack.com/enterprise/discovery/methods#file_tombstone for more details. """ + kwargs.update({"token": token, "file": file, "title": title, "content": content}) + return self.api_call("discovery.file.tombstone", http_method="POST", params=kwargs) - kwargs.update( - {"token": token, "file": file, "title": title, "content": content} - ) - return self.api_call( - "discovery.file.tombstone", http_method="POST", params=kwargs - ) - - def discovery_file_restore( - self, *, token: Optional[str] = None, file: str, **kwargs - ) -> DiscoveryResponse: + def discovery_file_restore(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """Restores a tombstoned file, making it accessible again. Refer to https://api.slack.com/enterprise/discovery/methods#file_restore for more details. """ @@ -691,13 +646,9 @@ def discovery_file_restore( "file": file, } ) - return self.api_call( - "discovery.file.restore", http_method="POST", params=kwargs - ) + return self.api_call("discovery.file.restore", http_method="POST", params=kwargs) - def discovery_file_delete( - self, *, token: Optional[str] = None, file: str, **kwargs - ) -> DiscoveryResponse: + def discovery_file_delete(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """Deletes a file. Refer to https://api.slack.com/enterprise/discovery/methods#file_delete for more details. """ @@ -709,9 +660,7 @@ def discovery_file_delete( ) return self.api_call("discovery.file.delete", http_method="POST", params=kwargs) - def discovery_files_release( - self, *, token: Optional[str] = None, files: str, **kwargs - ) -> DiscoveryResponse: + def discovery_files_release(self, *, token: Optional[str] = None, files: str, **kwargs) -> DiscoveryResponse: """The discovery.files.release endpoint can be used to release files that that been auto-tombstoned by the pre-processing setting. The endpoint accepts an array of files that should be released for viewing in the UI. Refer to https://api.slack.com/enterprise/discovery/methods#files_release for more details. @@ -722,6 +671,4 @@ def discovery_files_release( "files": files, } ) - return self.api_call( - "discovery.files.release", http_method="POST", params=kwargs - ) + return self.api_call("discovery.files.release", http_method="POST", params=kwargs) diff --git a/slack_discovery_sdk/examples/DLP_call_pattern.py b/slack_discovery_sdk/examples/DLP_call_pattern.py index 8bcbdf9..582588b 100644 --- a/slack_discovery_sdk/examples/DLP_call_pattern.py +++ b/slack_discovery_sdk/examples/DLP_call_pattern.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os +import logging +import os from slack_discovery_sdk import DiscoveryClient # type: ignore from slack_sdk import WebClient @@ -34,15 +35,11 @@ # conversation from each channel for conversation in last_24_hour_conversations["channels"]: - channel_conversation = client.discovery_conversations_history( - channel=conversation["id"], team=conversation["team"] - ) + channel_conversation = client.discovery_conversations_history(channel=conversation["id"], team=conversation["team"]) for message in channel_conversation["messages"]: # Step 3 - check each message and see if it contains a credit card number. If it does, tombstone the message. # A valid credit card for our logic is something like the following: '5122-2368-7954-3214' # Please note this is just example logic, to help you understand how to use the Discovery APIs. if is_credit_card_number(message["text"]): - client.discovery_chat_tombstone( - ts=message["ts"], channel=conversation["id"], team=message["team"] - ) + client.discovery_chat_tombstone(ts=message["ts"], channel=conversation["id"], team=message["team"]) diff --git a/slack_discovery_sdk/examples/__init__.py b/slack_discovery_sdk/examples/__init__.py index 39da80d..9d22545 100644 --- a/slack_discovery_sdk/examples/__init__.py +++ b/slack_discovery_sdk/examples/__init__.py @@ -2,6 +2,8 @@ # pytype: skip-file """The Slack Web API allows you to build applications that interact with Slack -in more complex ways than the integrations we provide out of the box.""" +in more complex ways than the integrations we provide out of the box. +""" + from .. import slack_discovery_sdk # noqa from . import utils # noqa diff --git a/slack_discovery_sdk/examples/audit_logs_pattern.py b/slack_discovery_sdk/examples/audit_logs_pattern.py index 67102fc..83f2815 100644 --- a/slack_discovery_sdk/examples/audit_logs_pattern.py +++ b/slack_discovery_sdk/examples/audit_logs_pattern.py @@ -1,6 +1,8 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os, json +import logging +import os +import json from slack_discovery_sdk import DiscoveryClient # type: ignore from utils import export_json_to_file # type: ignore diff --git a/slack_discovery_sdk/examples/get_enterprise_info.py b/slack_discovery_sdk/examples/get_enterprise_info.py index edc143c..cf25a4e 100644 --- a/slack_discovery_sdk/examples/get_enterprise_info.py +++ b/slack_discovery_sdk/examples/get_enterprise_info.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os +import logging +import os from slack_discovery_sdk import DiscoveryClient # type: ignore logging.basicConfig(level=logging.DEBUG) diff --git a/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py b/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py index 083c96b..52797be 100644 --- a/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py +++ b/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py @@ -1,6 +1,8 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os, json +import logging +import os +import json from slack_discovery_sdk import DiscoveryClient # type: ignore from utils import export_json_to_file # type: ignore @@ -38,9 +40,7 @@ # Step 3 - Retrieve the message history for each conversation returned in Step 2 # using discovery.conversations.history - channel_conversation = client.discovery_conversations_history( - channel=channel_id, team=team_id - ) + channel_conversation = client.discovery_conversations_history(channel=channel_id, team=team_id) channel_conversation_json = json.dumps(channel_conversation.body, indent=4) export_json_to_file( new_items=channel_conversation_json, diff --git a/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py b/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py index 3cd646c..e1fe853 100644 --- a/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py +++ b/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py @@ -1,6 +1,8 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os, json +import logging +import os +import json from slack_discovery_sdk import DiscoveryClient # type: ignore from utils import export_json_to_file # type: ignore @@ -38,9 +40,7 @@ # Step 3 - Retrieve the message history for each conversation returned in Step 2 # using discovery.conversations.history - channel_conversation = client.discovery_conversations_history( - channel=channel_id, team=team_id - ) + channel_conversation = client.discovery_conversations_history(channel=channel_id, team=team_id) channel_conversation_json = json.dumps(channel_conversation.body, indent=4) @@ -54,9 +54,7 @@ user_id=user_id, ) else: - edits_response = client.discovery_conversations_edits( - channel=channel_id, team=team_id - ) + edits_response = client.discovery_conversations_edits(channel=channel_id, team=team_id) # If has_edits is true, merge the edits into the conversation history file. channel_conversation.body["edits"] = edits_response["edits"] edits_response_json = json.dumps(channel_conversation.body, indent=4) diff --git a/slack_discovery_sdk/examples/utils.py b/slack_discovery_sdk/examples/utils.py index 0a15b8c..da87463 100644 --- a/slack_discovery_sdk/examples/utils.py +++ b/slack_discovery_sdk/examples/utils.py @@ -1,6 +1,9 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import datetime, os, re, shutil +import datetime +import os +import re +import shutil FILE_EXTENSION = ".json" @@ -19,6 +22,7 @@ def export_json_to_file( """This method is used to save data from the eDiscovery, DLP, and SIEM call patterns. This is just for example use, to make our partners and customers life easier. This is not meant to be a production implementation by any means. + Args: new_items: this is the JSON response from the discovery APIs that we want to save. logs_type: this is the discovery API method used @@ -47,6 +51,7 @@ def create_folder_for_channel( ) -> str: """This method will create a folder to keep all output from the discovery calls organized. It will create a folder based on channelID for a particular user: for example C02642201. + Args: base_dir: base directory channel_id: channel ID @@ -55,7 +60,6 @@ def create_folder_for_channel( Returns: Str which represents the channel """ - current_day = datetime.date.today() formatted_date = datetime.date.strftime(current_day, "%Y/%m/%d") diff --git a/slack_discovery_sdk/internal_utils.py b/slack_discovery_sdk/internal_utils.py index 8997f12..6e355eb 100644 --- a/slack_discovery_sdk/internal_utils.py +++ b/slack_discovery_sdk/internal_utils.py @@ -1,6 +1,9 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import platform, string, random, time +import platform +import string +import random +import time import sys from typing import Dict, Union, Optional, Any from urllib.parse import urljoin @@ -8,13 +11,12 @@ from .version import __version__ # type:ignore -def convert_bool_to_0_or_1( - params: Optional[Dict[str, Any]] -) -> Optional[Dict[str, Any]]: +def convert_bool_to_0_or_1(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: """Converts all bool values in dict to "0" or "1". Slack APIs safely accept "0"/"1" as boolean values. Using True/False (bool in Python) doesn't work with aiohttp. This method converts only the bool values in top-level of a given dict. + Args: params: params as a dict Returns: @@ -28,6 +30,7 @@ def convert_bool_to_0_or_1( def get_user_agent(prefix: Optional[str] = None, suffix: Optional[str] = None): """Construct the user-agent header with the package info, Python version and OS version. + Returns: The user agent string. e.g. 'Python/3.6.7 slack_discovery_sdk/1.0.0 Darwin/17.7.0' @@ -44,6 +47,7 @@ def get_user_agent(prefix: Optional[str] = None, suffix: Optional[str] = None): def _get_url(base_url: str, api_method: str) -> str: """Joins the base Slack URL and an API method to form an absolute URL. + Args: base_url (str): The base URL api_method (str): The Slack Web API method. e.g. 'discovery.chat.delete' @@ -57,6 +61,7 @@ def _get_url(base_url: str, api_method: str) -> str: def _next_cursor_is_present(data) -> bool: """Determine if the response contains 'next_cursor' and 'next_cursor' is not empty. + Returns: A boolean value. """ @@ -76,9 +81,7 @@ def _to_0_or_1_if_bool(v: Any) -> Union[Any, str]: def _build_unexpected_body_error_message(body: str) -> str: - body_for_logging = "".join( - [line.strip() for line in body.replace("\r", "\n").split("\n")] - ) + body_for_logging = "".join([line.strip() for line in body.replace("\r", "\n").split("\n")]) if len(body_for_logging) > 100: body_for_logging = body_for_logging[:100] + "..." message = f"Received a response in a non-JSON format: {body_for_logging}" @@ -87,9 +90,7 @@ def _build_unexpected_body_error_message(body: str) -> str: def get_random_string(length: int = 10) -> str: all_ascii_lowercase_chars = string.ascii_lowercase - random_string = "".join( - random.choice(all_ascii_lowercase_chars) for _ in range(length) - ) + random_string = "".join(random.choice(all_ascii_lowercase_chars) for _ in range(length)) return random_string diff --git a/slack_discovery_sdk/proxy_support.py b/slack_discovery_sdk/proxy_support.py index d77baab..29f87aa 100644 --- a/slack_discovery_sdk/proxy_support.py +++ b/slack_discovery_sdk/proxy_support.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. """Internal module for loading proxy-related env variables""" + import logging import os from typing import Optional @@ -16,7 +17,5 @@ def load_http_proxy_from_env(logger: logging.Logger = _default_logger) -> Option or os.environ.get("http_proxy") ) if proxy_url is not None: - logger.debug( - f"HTTP proxy URL has been loaded from an env variable: {proxy_url}" - ) + logger.debug(f"HTTP proxy URL has been loaded from an env variable: {proxy_url}") return proxy_url diff --git a/slack_discovery_sdk/rate_limit_support.py b/slack_discovery_sdk/rate_limit_support.py index 6e53d1e..ab62eaf 100644 --- a/slack_discovery_sdk/rate_limit_support.py +++ b/slack_discovery_sdk/rate_limit_support.py @@ -76,20 +76,14 @@ def append_api_call_timestamp(self, api_method: str): with self.lock: now = time.time() self.org_call_histories_in_last_second.append(now) - api_method_histories = self.api_method_call_histories_in_last_minute.get( - api_method, [] - ) + api_method_histories = self.api_method_call_histories_in_last_minute.get(api_method, []) api_method_histories.append(now) - self.api_method_call_histories_in_last_minute[ - api_method - ] = api_method_histories + self.api_method_call_histories_in_last_minute[api_method] = api_method_histories def append_api_call_result(self, api_method: str, is_success: bool): with self.lock: if is_success is True: - new_count = ( - self.api_method_successful_call_counts.get(api_method, 0) + 1 - ) + new_count = self.api_method_successful_call_counts.get(api_method, 0) + 1 self.api_method_successful_call_counts[api_method] = new_count else: new_count = self.api_method_failed_call_counts.get(api_method, 0) + 1 @@ -100,9 +94,7 @@ def calculate_sleep_duration(self, api_method: str) -> float: sleep_seconds = 0 # The estimated count of all the requests performed in the last second - last_second_org_call_count = ( - len(self.org_call_histories_in_last_second) * self.number_of_nodes - ) + last_second_org_call_count = len(self.org_call_histories_in_last_second) * self.number_of_nodes # Calculate the sleep_seconds considering the last second traffic if last_second_org_call_count >= 10: @@ -121,10 +113,8 @@ def calculate_sleep_duration(self, api_method: str) -> float: last_minute_api_method_call_count = len(last_minutes_api_method_requests) # Calculate the sleep_seconds considering the last minute traffic toward the endpoint - max_requests_for_api_method = ( - self.max_requests_per_minute_for_each_api_method.get( - api_method, self.MAX_REQUESTS_PER_MINUTE_FOR_API_METHOD - ) + max_requests_for_api_method = self.max_requests_per_minute_for_each_api_method.get( + api_method, self.MAX_REQUESTS_PER_MINUTE_FOR_API_METHOD ) denominator = max_requests_for_api_method / 15 # this value is usually 80 if last_minute_api_method_call_count >= max_requests_for_api_method * 0.9: @@ -139,17 +129,12 @@ def calculate_sleep_duration(self, api_method: str) -> float: # Change the pace from 60 seconds to 30 seconds sleep_seconds = 30 / denominator - if ( - max_requests_for_api_method >= 120 - and last_minute_api_method_call_count >= max_requests_for_api_method / 120 - ): + if max_requests_for_api_method >= 120 and last_minute_api_method_call_count >= max_requests_for_api_method / 120: # Burst traffic: # Change the pace from 60 seconds to 180 seconds three_seconds_ago = time.time() - 3 requests_in_last_three_seconds = [ - timestamp - for timestamp in last_minutes_api_method_requests - if timestamp >= three_seconds_ago + timestamp for timestamp in last_minutes_api_method_requests if timestamp >= three_seconds_ago ] if len(requests_in_last_three_seconds) >= max_requests_for_api_method / 120: sleep_seconds = 180 / denominator @@ -166,8 +151,7 @@ def generate_metrics_report( "enterprise_id": self.enterprise_id, "last_second_requests": len(self.org_call_histories_in_last_second), "last_minute_requests_per_api_method": { - k: len(v) - for k, v in self.api_method_call_histories_in_last_minute.items() + k: len(v) for k, v in self.api_method_call_histories_in_last_minute.items() }, "successful_call_counts": self.api_method_successful_call_counts, "failed_call_counts": self.api_method_failed_call_counts, diff --git a/slack_discovery_sdk/response.py b/slack_discovery_sdk/response.py index 6fb84d7..551361d 100644 --- a/slack_discovery_sdk/response.py +++ b/slack_discovery_sdk/response.py @@ -20,22 +20,26 @@ class DiscoveryResponse: """An iterable container of response data. + Attributes: body (dict): The json-encoded content of the response. Along with the headers and status code information. + Methods: validate: Check if the response from Slack was successful. get: Retrieves any key from the response data. next: Retrieves the next portion of results, if 'next_cursor' is present. + Example: ```python import os from slack_discovery_sdk import DiscoveryClient - client = DiscoveryClient(token=os.environ['SLACK_ORG_ADMIN_TOKEN']) + + client = DiscoveryClient(token=os.environ["SLACK_ORG_ADMIN_TOKEN"]) users = [] for page in client.discovery_users_list(): - users = users + page['members'] + users = users + page["members"] ``` Note: Some responses return collections of information @@ -81,10 +85,12 @@ def __str__(self): def __getitem__(self, key): """Retrieves any key from the data store. + Note: This is implemented so users can reference the SlackResponse object like a dictionary. e.g. response["ok"] + Returns: The value from data or None. """ @@ -93,8 +99,10 @@ def __getitem__(self, key): def __iter__(self): """Enables the ability to iterate over the response. It's required for the iterator protocol. + Note: This enables Slack cursor-based pagination. + Returns: (SlackResponse) self """ @@ -104,6 +112,7 @@ def __iter__(self): def __next__(self): """Retrieves the next portion of results, if 'next_cursor' is present. + Note: Some responses return collections of information like channel and user lists. If they do it's likely @@ -111,9 +120,11 @@ def __next__(self): method allows you to iterate over the response until your code hits 'break' or there are no more results to be found. + Returns: (SlackResponse) self With the new response data now attached to this object. + Raises: SlackApiError: If the request to the Slack API failed. StopIteration: If 'next_cursor' is not present or empty. @@ -129,12 +140,7 @@ def __next__(self): # offset for https://api.slack.com/enterprise/discovery/methods#users_list etc. params.update({"offset": self.body.get("offset")}) - if any( - [ - latest_offset_api in self.api_url - for latest_offset_api in _LATEST_OFFSET_APIS - ] - ): + if any([latest_offset_api in self.api_url for latest_offset_api in _LATEST_OFFSET_APIS]): params.update({"latest": self.body.get("offset")}) response = self._client.fetch_next_page( # skipcq: PYL-W0212 @@ -152,10 +158,12 @@ def __next__(self): def get(self, key, default=None): """Retrieves any key from the response data. + Note: This is implemented so users can reference the SlackResponse object like a dictionary. e.g. response.get("ok", False) + Returns: The value from data or the specified default. """ @@ -163,17 +171,14 @@ def get(self, key, default=None): def validate(self): """Check if the response from Slack was successful. + Returns: (SlackResponse) This method returns it's own object. e.g. 'self' Raises: SlackApiError: The request to the Slack API failed. """ - if ( - self.status_code == 200 - and self.body is not None - and self.body.get("ok", False) - ): + if self.status_code == 200 and self.body is not None and self.body.get("ok", False): return self msg = "The request to the Slack API failed." raise DiscoveryApiError(message=msg, response=self) diff --git a/tests/test_chat.py b/tests/test_chat.py index b698ae0..000d39f 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -19,9 +19,7 @@ def setup_method(self): self.team = os.environ[SLACK_DISCOVERY_SDK_TEST_TEAM_ID] self.channel = os.environ[SLACK_DISCOVERY_SDK_TEST_CHANNEL_ID] self.client = DiscoveryClient(token=self.token) - self.web_client = WebClient( - token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN] - ) + self.web_client = WebClient(token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN]) def test_tombstone(self): expected_message_subtype = "dlp_tombstone" @@ -112,17 +110,13 @@ def test_delete(self): ) def test_restore(self): - restore_msg_text = ( - "The Discovery API will first tombstone this message and then restore it..." - ) + restore_msg_text = "The Discovery API will first tombstone this message and then restore it..." try: conversations = self.web_client.users_conversations(team_id=self.team) assert conversations.get("error") is None tombstone_channel = conversations["channels"][0]["id"] - message_to_restore = self.web_client.chat_postMessage( - channel=tombstone_channel, text=restore_msg_text - ) + message_to_restore = self.web_client.chat_postMessage(channel=tombstone_channel, text=restore_msg_text) assert message_to_restore.get("error") is None tombstone_msg_resp = self.client.discovery_chat_tombstone( diff --git a/tests/test_conversations.py b/tests/test_conversations.py index dc4f3db..cb3aa0c 100644 --- a/tests/test_conversations.py +++ b/tests/test_conversations.py @@ -1,7 +1,9 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -from typing import Any -import os, pytest, time, json +import os +import pytest +import time +import json from slack_sdk import WebClient from slack_discovery_sdk import DiscoveryClient from slack_discovery_sdk.internal_utils import ( @@ -23,9 +25,7 @@ def setup_method(self): self.team = os.environ[SLACK_DISCOVERY_SDK_TEST_TEAM_ID] self.channel = os.environ[SLACK_DISCOVERY_SDK_TEST_CHANNEL_ID] self.client = DiscoveryClient(token=self.token) - self.web_client = WebClient( - token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN] - ) + self.web_client = WebClient(token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN]) def test_conversations_search(self): first_msg_text = "This message will test the search API" @@ -96,9 +96,7 @@ def test_conversations_history_pagination(self): conversations = [] limit_size = 1 page_num = 0 - for page in self.client.discovery_conversations_history( - channel=self.channel, team=self.team, limit=limit_size - ): + for page in self.client.discovery_conversations_history(channel=self.channel, team=self.team, limit=limit_size): for message in page["messages"]: conversations.append(json.dumps(message)) page_num += 1 @@ -131,11 +129,7 @@ def test_conversations_history_from_one_minute_ago(self): # if there are multiple messages in the last minute, one of them should be the one from above found = next( - ( - message["text"] - for message in response["messages"] - if message["text"] == test_text - ), + (message["text"] for message in response["messages"] if message["text"] == test_text), None, ) assert found == test_text @@ -151,9 +145,7 @@ def test_conversations_history_from_one_minute_ago(self): def test_conversations_edits_from_one_minute_ago(self): # this test will create a message, edit it, and find edited messgages in the last minute - updated_text = ( - "this message has been edited via chat_updateMessage API in a test" - ) + updated_text = "this message has been edited via chat_updateMessage API in a test" msg_to_edit = None try: msg_to_edit = self.web_client.chat_postMessage( @@ -177,11 +169,7 @@ def test_conversations_edits_from_one_minute_ago(self): assert response["error"] is None # if there are more than one edits, one of them should be the one from above found = next( - ( - edit["text"] - for edit in response["edits"] - if edit["text"] == updated_text - ), + (edit["text"] for edit in response["edits"] if edit["text"] == updated_text), None, ) assert found == updated_text @@ -202,17 +190,11 @@ def test_conversations_info_for_private_channel(self): # create channel for testing purposes - make sure we can get info on this channel test_channel = self.create_channel() test_channel_creation_time = test_channel["channel"]["created"] - response = self.client.discovery_conversations_info( - team=self.team, channel=test_channel["channel"]["id"] - ) + response = self.client.discovery_conversations_info(team=self.team, channel=test_channel["channel"]["id"]) assert response["error"] is None # if there are multiple channels, ensure we can find the one we created above found = next( - ( - info["created"] - for info in response["info"] - if info["created"] == test_channel_creation_time - ), + (info["created"] for info in response["info"] if info["created"] == test_channel_creation_time), None, ) assert found == test_channel_creation_time @@ -220,30 +202,20 @@ def test_conversations_info_for_private_channel(self): finally: # delete the test channel we created above if test_channel is not None: - self.web_client.conversations_archive( - channel=test_channel["channel"]["id"] - ) + self.web_client.conversations_archive(channel=test_channel["channel"]["id"]) def test_conversations_members_new_channel(self): test_channel = None try: test_channel = self.create_channel() - convo_join_resp = self.web_client.conversations_join( - channel=test_channel["channel"]["id"] - ) + convo_join_resp = self.web_client.conversations_join(channel=test_channel["channel"]["id"]) channel_creator = convo_join_resp["channel"]["creator"] - response = self.client.discovery_conversations_members( - team=self.team, channel=test_channel["channel"]["id"] - ) + response = self.client.discovery_conversations_members(team=self.team, channel=test_channel["channel"]["id"]) assert response["error"] is None # loop through members to ensure the creator is one of the members of the channel found = next( - ( - member["id"] - for member in response["members"] - if member["id"] == channel_creator - ), + (member["id"] for member in response["members"] if member["id"] == channel_creator), None, ) assert found == channel_creator @@ -251,9 +223,7 @@ def test_conversations_members_new_channel(self): finally: # delete the test channel we created above if test_channel is not None: - self.web_client.conversations_archive( - channel=test_channel["channel"]["id"] - ) + self.web_client.conversations_archive(channel=test_channel["channel"]["id"]) def test_conversations_renames(self): test_channel = None @@ -261,23 +231,15 @@ def test_conversations_renames(self): test_channel = self.create_channel() new_channel_name = get_random_string() - self.web_client.conversations_rename( - channel=test_channel["channel"]["id"], name=new_channel_name - ) + self.web_client.conversations_rename(channel=test_channel["channel"]["id"], name=new_channel_name) # check for renames from the last minute, which should include the rename from above - response = self.client.discovery_conversations_renames( - team=self.team, oldest=get_timestamp_last_minute() - ) + response = self.client.discovery_conversations_renames(team=self.team, oldest=get_timestamp_last_minute()) assert response["error"] is None # if there are multiple renames, one of them should be the one from above found = next( - ( - rename["new_name"] - for rename in response["renames"] - if rename["new_name"] == new_channel_name - ), + (rename["new_name"] for rename in response["renames"] if rename["new_name"] == new_channel_name), None, ) assert found == new_channel_name @@ -285,9 +247,7 @@ def test_conversations_renames(self): finally: # delete the test channel we created above if test_channel is not None: - self.web_client.conversations_archive( - channel=test_channel["channel"]["id"] - ) + self.web_client.conversations_archive(channel=test_channel["channel"]["id"]) def test_conversations_reactions(self): test_text = "This message will test reactions" @@ -325,11 +285,7 @@ def test_conversations_reactions(self): assert response["error"] is None # if we have more than one reaction (which we should) check to make sure we have thumbs reaction found = next( - ( - reaction["name"] - for reaction in response["reactions"] - if reaction["name"] == smile_reaction - ), + (reaction["name"] for reaction in response["reactions"] if reaction["name"] == smile_reaction), None, ) assert found == smile_reaction diff --git a/tests/test_draft.py b/tests/test_draft.py index ea038ff..11f664c 100644 --- a/tests/test_draft.py +++ b/tests/test_draft.py @@ -45,7 +45,5 @@ def test_draft_info(self): user = response["drafts"][0]["user_id"] team = response["drafts"][0]["team_id"] draft = response["drafts"][0]["id"] - info_response = self.client.discovery_draft_info( - team=team, draft=draft, user=user, limit=resp_limit - ) + info_response = self.client.discovery_draft_info(team=team, draft=draft, user=user, limit=resp_limit) assert info_response["error"] is None diff --git a/tests/test_file.py b/tests/test_file.py index ed9ca49..cd6b6f9 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -20,9 +20,7 @@ def setup_method(self): self.team = os.environ[SLACK_DISCOVERY_SDK_TEST_TEAM_ID] self.channel = os.environ[SLACK_DISCOVERY_SDK_TEST_CHANNEL_ID] self.client = DiscoveryClient(token=self.token) - self.web_client = WebClient( - token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN] - ) + self.web_client = WebClient(token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN]) def test_files_list(self): resp_limit = 2 @@ -64,10 +62,7 @@ def test_file_tombstone(self): file_upload = self.create_file() file_id = file_upload["file"]["id"] file_tombstone_resp = self.client.discovery_file_tombstone(file=file_id) - assert ( - file_id == file_tombstone_resp["file"]["id"] - and file_tombstone_resp["file"]["is_tombstoned"] is True - ) + assert file_id == file_tombstone_resp["file"]["id"] and file_tombstone_resp["file"]["is_tombstoned"] is True finally: # clean up the test file - first we have to restore, then we can delete self.client.discovery_file_restore(file=file_upload["file"]["id"]) @@ -79,13 +74,8 @@ def test_file_restore(self): file_upload = self.create_file() file_id = file_upload["file"]["id"] self.client.discovery_file_tombstone(file=file_id) - file_restore_resp = self.client.discovery_file_restore( - file=file_upload["file"]["id"] - ) - assert ( - file_id == file_restore_resp["file"]["id"] - and file_restore_resp["file"]["is_tombstoned"] is False - ) + file_restore_resp = self.client.discovery_file_restore(file=file_upload["file"]["id"]) + assert file_id == file_restore_resp["file"]["id"] and file_restore_resp["file"]["is_tombstoned"] is False finally: # clean up the test file - first we have to restore, then we can delete self.web_client.files_delete(file=file_upload["file"]["id"]) @@ -95,12 +85,8 @@ def test_file_delete(self): try: file_upload = self.create_file() file_id = file_upload["file"]["id"] - file_delete_resp = self.client.discovery_file_delete( - file=file_upload["file"]["id"] - ) - assert ( - file_id == file_delete_resp["file"] and file_delete_resp["ok"] is True - ) + file_delete_resp = self.client.discovery_file_delete(file=file_upload["file"]["id"]) + assert file_id == file_delete_resp["file"] and file_delete_resp["ok"] is True finally: # can pass as we already delete file above pass @@ -114,10 +100,7 @@ def test_single_file_release(self): self.client.discovery_file_tombstone(file=file_id) # release the file files_release_resp = self.client.discovery_files_release(files=file_id) - assert ( - file_id == files_release_resp["files"][0]["file"]["id"] - and len(files_release_resp["failed_files"]) == 0 - ) + assert file_id == files_release_resp["files"][0]["file"]["id"] and len(files_release_resp["failed_files"]) == 0 finally: # clean up the test file - first we have to restore, then we can delete self.web_client.files_delete(file=file_upload["file"]["id"]) @@ -141,9 +124,7 @@ def test_multiple_file_release(self): files_to_release.append(file_id_1) files_to_release.append(file_id_2) # release the file - files_release_resp = self.client.discovery_files_release( - files=files_to_release - ) + files_release_resp = self.client.discovery_files_release(files=files_to_release) assert len(files_release_resp["failed_files"]) == 0 finally: diff --git a/tests/test_rate_limit_scenario.py b/tests/test_rate_limit_scenario.py index 97881bc..7495a1a 100644 --- a/tests/test_rate_limit_scenario.py +++ b/tests/test_rate_limit_scenario.py @@ -55,18 +55,14 @@ def test_discovery_conversations_search(self): @pytest.mark.skip def test_discovery_conversations_list(self): executor = ThreadPoolExecutor(max_workers=100) - client = DiscoveryClient( - token=self.token, rate_limit_error_prevention_enabled=True - ) + client = DiscoveryClient(token=self.token, rate_limit_error_prevention_enabled=True) def run(): for i in range(10): for page in client.discovery_conversations_list(limit=10): assert page.status_code == 200 for channel in page.get("channels"): - response = client.discovery_conversations_info( - channel=channel.get("id") - ) + response = client.discovery_conversations_info(channel=channel.get("id")) assert response.status_code == 200 try: diff --git a/tests/test_rate_limit_support.py b/tests/test_rate_limit_support.py index b5ec4c3..62dbedb 100644 --- a/tests/test_rate_limit_support.py +++ b/tests/test_rate_limit_support.py @@ -35,11 +35,4 @@ def test_cleanup(self): rate_limiter.cleanup() assert len(rate_limiter.org_call_histories_in_last_second) == 3 - assert ( - len( - rate_limiter.api_method_call_histories_in_last_minute[ - "discovery.enterprise.info" - ] - ) - == 3 - ) + assert len(rate_limiter.api_method_call_histories_in_last_minute["discovery.enterprise.info"]) == 3 From ce9e172d99bb4ce94a3e240656512fc41c0b08f8 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:50:47 -0500 Subject: [PATCH 4/8] docs: fix docstrings flagged by ruff pydocstyle Split each docstring summary onto its own line with a blank line after it, end summaries with a period, and document the missing args, so the google convention checks pass with the same ignores as the other python repos. Co-Authored-By: Claude --- slack_discovery_sdk/__init__.py | 5 +- slack_discovery_sdk/base_client.py | 10 ++-- slack_discovery_sdk/client.py | 74 +++++++++++++++++------- slack_discovery_sdk/errors.py | 4 +- slack_discovery_sdk/examples/__init__.py | 5 +- slack_discovery_sdk/examples/utils.py | 7 ++- slack_discovery_sdk/internal_utils.py | 7 +-- slack_discovery_sdk/proxy_support.py | 2 +- slack_discovery_sdk/response.py | 1 + 9 files changed, 76 insertions(+), 39 deletions(-) diff --git a/slack_discovery_sdk/__init__.py b/slack_discovery_sdk/__init__.py index c7cc630..4af1680 100644 --- a/slack_discovery_sdk/__init__.py +++ b/slack_discovery_sdk/__init__.py @@ -1,8 +1,9 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. # pytype: skip-file -"""The Slack Web API allows you to build applications that interact with Slack -in more complex ways than the integrations we provide out of the box. +"""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 .client import DiscoveryClient diff --git a/slack_discovery_sdk/base_client.py b/slack_discovery_sdk/base_client.py index 7073049..8120919 100644 --- a/slack_discovery_sdk/base_client.py +++ b/slack_discovery_sdk/base_client.py @@ -157,7 +157,8 @@ def fetch_next_page( headers: Dict[str, str], params: Dict[str, str], ) -> Dict[str, any]: # type:ignore - """This method is supposed to be used only for DiscoveryResponse pagination + """This method is supposed to be used only for DiscoveryResponse pagination. + You can paginate using Python's for iterator as below: for response in client.conversations_list(limit=100): # do something with each response here @@ -187,6 +188,7 @@ def _urllib_api_call( Args: token: Slack API Token (either bot token or user token) + http_method: HTTP method (e.g., POST) url: Complete URL (e.g., https://slack.com/api/discovery.enterprise.info) params: Form body params additional_headers: Request headers to append @@ -237,10 +239,10 @@ def _perform_urllib_http_request( """Performs an HTTP request and parses the response. Args: + http_method: HTTP method (e.g., POST) url: Complete URL (e.g., https://slack.com/api/discovery.enterprise.info) - args: args has "headers" and "params" - "headers": Dict[str, str] - "params": Dict[str, str], + headers: Request headers + params: Form body params Returns: dict {status: int, headers: Headers, body: str} diff --git a/slack_discovery_sdk/client.py b/slack_discovery_sdk/client.py index 444c435..05dd924 100644 --- a/slack_discovery_sdk/client.py +++ b/slack_discovery_sdk/client.py @@ -11,11 +11,13 @@ class DiscoveryClient(BaseDiscoveryClient): """A DiscoveryClient allows apps to communicate with the Slack Platform's Discovery APIs. + https://api.slack.com/enterprise/discovery/methods """ def auth_test(self, **kwargs) -> DiscoveryResponse: """Checks authentication & identity. + Refer to https://api.slack.com/methods/auth.test for more details. """ return self.api_call("auth.test", http_method="POST", params=kwargs) @@ -36,6 +38,7 @@ def oauth_v2_access( **kwargs, ) -> DiscoveryResponse: """Exchanges a temporary OAuth verifier code for an access token. + Refer to https://api.slack.com/methods/oauth.v2.access for more details. """ if redirect_uri is not None: @@ -66,8 +69,9 @@ def discovery_enterprise_info( include_deleted: Optional[bool] = None, **kwargs, ) -> DiscoveryResponse: - """This method returns basic information about the Enterprise Grid org - where the app is installed, including all workspaces (teams). + """This method returns basic information about the Enterprise Grid org where the app is installed. + + It includes all workspaces (teams). The teams array is paged at 1000 items by default, but this can also be shortened with the limit parameter. Refer to https://api.slack.com/enterprise/discovery/methods#enterprise_info for more details. """ @@ -94,8 +98,9 @@ def discovery_users_list( offset: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """Very similar to regular users.list method. Includes an array of workspace IDs - that the user belongs to on a Grid org (teams). + """Very similar to regular users.list method. + + Includes an array of workspace IDs that the user belongs to on a Grid org (teams). Refer to https://api.slack.com/enterprise/discovery/methods#users_list for more details. """ kwargs.update( @@ -117,6 +122,7 @@ def discovery_user_info( **kwargs, ) -> DiscoveryResponse: """Get information on a single user in an Enterprise. + The processes for getting info about internal and external users are slightly different. Refer to https://api.slack.com/enterprise/discovery/methods#user_info for more details. """ @@ -137,8 +143,9 @@ def discovery_user_conversations( limit: Optional[int] = None, **kwargs, ) -> DiscoveryResponse: - """This method lists IDs for all conversations (channels and DMs, including public, private, - org-wide, and shared) a user is in. + """This method lists IDs for all conversations a user is in. + + This includes channels and DMs: public, private, org-wide, and shared. Refer to https://api.slack.com/enterprise/discovery/methods#user_conversations for more details. """ kwargs.update( @@ -171,8 +178,9 @@ def discovery_conversations_recent( limit: Optional[int] = None, **kwargs, ) -> DiscoveryResponse: - """By default this method will return all updated conversations - (including org-shared and externally-shared conversations) + """This method returns the conversations updated across the Grid org. + + By default it returns all updated conversations (including org-shared and externally-shared conversations) from the entire Grid org for the 24 hours preceding the call. You can restrict it to a specific workspace within an org, a smaller timespan, or to return data for the last 7 days by using the optional parameters. @@ -195,8 +203,9 @@ def discovery_conversations_list( limit: Optional[int] = None, **kwargs, ) -> DiscoveryResponse: - """This method provides a paginated list of all conversations (channels, private channels/groups, DMs), - with just a subset of the channel information. + """This method provides a paginated list of all conversations. + + It covers channels, private channels/groups, and DMs, with just a subset of the channel information. Refer to https://api.slack.com/enterprise/discovery/methods#conversations_list for more details. """ kwargs.update( @@ -227,6 +236,7 @@ def discovery_conversations_history( **kwargs, ) -> DiscoveryResponse: """Retrieves the history of the channel-object. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_history for more details. """ if reactions is not None: @@ -259,6 +269,7 @@ def discovery_conversations_edits( **kwargs, ) -> DiscoveryResponse: """This method will only return edit and delete records of messages. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_edits for more details. """ kwargs.update( @@ -283,6 +294,7 @@ def discovery_conversations_info( **kwargs, ) -> DiscoveryResponse: """This method provides a comprehensive overview of a single channel outside of its message history. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_info for more details. """ kwargs.update( @@ -307,6 +319,7 @@ def discovery_conversations_members( **kwargs, ) -> DiscoveryResponse: """This method provides a list of everyone in a given channel, private channel, MDPM or DM. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_members for more details. """ kwargs.update( @@ -331,8 +344,9 @@ def discovery_conversations_renames( private: Optional[bool] = None, **kwargs, ) -> DiscoveryResponse: - """You can use this endpoint to gather all channel renames that have occured for an org, - without having to call the discovery.conversations.info endpoint for each channel. + """You can use this endpoint to gather all channel renames that have occured for an org. + + This avoids calling the discovery.conversations.info endpoint for each channel. Refer to https://api.slack.com/enterprise/discovery/methods#conversations_renames for more details. """ kwargs.update( @@ -358,6 +372,7 @@ def discovery_conversations_reactions( **kwargs, ) -> DiscoveryResponse: """Use this method to gather detailed information about current message reactions in a channel. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_reactions for more details. """ kwargs.update( @@ -385,8 +400,9 @@ def discovery_conversations_search( offset: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """The discovery.conversations.search endpoint can be used to find channels and messages within an - instance that contain the provided search term. + """The discovery.conversations.search endpoint can be used to find channels and messages. + + It returns those within an instance that contain the provided search term. Refer to https://api.slack.com/enterprise/discovery/methods#conversations_search for more details. """ kwargs.update( @@ -416,8 +432,9 @@ def discovery_chat_info( team: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """This endpoint returns a single message. If the message has been edited (or deleted), - this method returns the current, edited (or deleted) message. + """This endpoint returns a single message. + + If the message has been edited (or deleted), this method returns the current, edited (or deleted) message. Refer to https://api.slack.com/enterprise/discovery/methods#chat_info for more details. """ kwargs.update( @@ -441,8 +458,9 @@ def discovery_chat_update( attachments: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """Use this method for quarantine and restoration. This method specifies text or attachments that - should be included in place of the message. + """Use this method for quarantine and restoration. + + This method specifies text or attachments that should be included in place of the message. Refer to https://api.slack.com/enterprise/discovery/methods#chat_update for more details. """ kwargs.update( @@ -467,6 +485,7 @@ def discovery_chat_delete( **kwargs, ) -> DiscoveryResponse: """Deletes a message. This method purges the history, edits, and message from the Slack databases. + Refer to https://api.slack.com/enterprise/discovery/methods#chat_delete for more details. """ kwargs.update( @@ -490,6 +509,7 @@ def discovery_chat_tombstone( **kwargs, ) -> DiscoveryResponse: """Use this method to update and or obscure a message in the event that the message violated policy. + Refer to https://api.slack.com/enterprise/discovery/methods#chat_tombstone for more details. """ kwargs.update( @@ -513,6 +533,7 @@ def discovery_chat_restore( **kwargs, ) -> DiscoveryResponse: """Use this method to restore a tombstoned message to the client. + Refer to https://api.slack.com/enterprise/discovery/methods#chat_restore for more details. """ kwargs.update( @@ -541,6 +562,7 @@ def discovery_drafts_list( **kwargs, ) -> DiscoveryResponse: """The discovery.drafts.list method returns a list of drafts created upon the specified team. + Refer to https://api.slack.com/enterprise/discovery/methods#drafts_list for more details. """ kwargs.update( @@ -569,6 +591,7 @@ def discovery_draft_info( **kwargs, ) -> DiscoveryResponse: """The discovery.draft.info endpoint provides information associated with a singular draft. + Refer to https://api.slack.com/enterprise/discovery/methods#drafts_info for more details. """ kwargs.update( @@ -600,6 +623,7 @@ def discovery_files_list( **kwargs, ) -> DiscoveryResponse: """This method returns files uploaded within a specified timeframe. + Refer to https://api.slack.com/enterprise/discovery/methods#files_list for more details. """ kwargs.update( @@ -615,6 +639,7 @@ def discovery_files_list( def discovery_file_info(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """All file comments are shown here. File comments are Slack's odd message type. + Refer to https://api.slack.com/enterprise/discovery/methods#file_info for more details. """ kwargs.update({"token": token, "file": file}) @@ -629,8 +654,9 @@ def discovery_file_tombstone( content: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """Tombstone a file, making it inaccessible. Download the file in advance for inspection, - because it will not be accessible after tombstoning. + """Tombstone a file, making it inaccessible. + + Download the file in advance for inspection, because it will not be accessible after tombstoning. Refer to https://api.slack.com/enterprise/discovery/methods#file_tombstone for more details. """ kwargs.update({"token": token, "file": file, "title": title, "content": content}) @@ -638,6 +664,7 @@ def discovery_file_tombstone( def discovery_file_restore(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """Restores a tombstoned file, making it accessible again. + Refer to https://api.slack.com/enterprise/discovery/methods#file_restore for more details. """ kwargs.update( @@ -650,6 +677,7 @@ def discovery_file_restore(self, *, token: Optional[str] = None, file: str, **kw def discovery_file_delete(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """Deletes a file. + Refer to https://api.slack.com/enterprise/discovery/methods#file_delete for more details. """ kwargs.update( @@ -661,8 +689,10 @@ def discovery_file_delete(self, *, token: Optional[str] = None, file: str, **kwa return self.api_call("discovery.file.delete", http_method="POST", params=kwargs) def discovery_files_release(self, *, token: Optional[str] = None, files: str, **kwargs) -> DiscoveryResponse: - """The discovery.files.release endpoint can be used to release files that that been auto-tombstoned by the - pre-processing setting. The endpoint accepts an array of files that should be released for viewing in the UI. + """The discovery.files.release endpoint can be used to release files that have been auto-tombstoned. + + Files are auto-tombstoned by the pre-processing setting. + The endpoint accepts an array of files that should be released for viewing in the UI. Refer to https://api.slack.com/enterprise/discovery/methods#files_release for more details. """ kwargs.update( diff --git a/slack_discovery_sdk/errors.py b/slack_discovery_sdk/errors.py index 8a011b9..2ccb63e 100644 --- a/slack_discovery_sdk/errors.py +++ b/slack_discovery_sdk/errors.py @@ -1,10 +1,10 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -"""Errors that can be raised by this SDK""" +"""Errors that can be raised by this SDK.""" class DiscoveryClientError(Exception): - """Base class for Client errors""" + """Base class for Client errors.""" class DiscoveryRequestError(DiscoveryClientError): diff --git a/slack_discovery_sdk/examples/__init__.py b/slack_discovery_sdk/examples/__init__.py index 9d22545..5f7f331 100644 --- a/slack_discovery_sdk/examples/__init__.py +++ b/slack_discovery_sdk/examples/__init__.py @@ -1,8 +1,9 @@ # # Copyright 2021, Slack Technologies, LLC. All rights reserved. # pytype: skip-file -"""The Slack Web API allows you to build applications that interact with Slack -in more complex ways than the integrations we provide out of the box. +"""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 diff --git a/slack_discovery_sdk/examples/utils.py b/slack_discovery_sdk/examples/utils.py index da87463..ec727ca 100644 --- a/slack_discovery_sdk/examples/utils.py +++ b/slack_discovery_sdk/examples/utils.py @@ -20,11 +20,13 @@ def export_json_to_file( user_id: str, ): """This method is used to save data from the eDiscovery, DLP, and SIEM call patterns. + This is just for example use, to make our partners and customers life easier. This is not meant to be a production implementation by any means. Args: new_items: this is the JSON response from the discovery APIs that we want to save. + base_dir: the folder where the output is written logs_type: this is the discovery API method used channel_id: channel_id i.e C02449123 user_id: The ID of the user i.e. U09123411 @@ -49,8 +51,9 @@ def create_folder_for_channel( channel_id: str, user_id: str, ) -> str: - """This method will create a folder to keep all output from the discovery calls - organized. It will create a folder based on channelID for a particular user: for example C02642201. + """This method will create a folder to keep all output from the discovery calls organized. + + It will create a folder based on channelID for a particular user: for example C02642201. Args: base_dir: base directory diff --git a/slack_discovery_sdk/internal_utils.py b/slack_discovery_sdk/internal_utils.py index 6e355eb..c3e7b73 100644 --- a/slack_discovery_sdk/internal_utils.py +++ b/slack_discovery_sdk/internal_utils.py @@ -13,6 +13,7 @@ def convert_bool_to_0_or_1(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: """Converts all bool values in dict to "0" or "1". + Slack APIs safely accept "0"/"1" as boolean values. Using True/False (bool in Python) doesn't work with aiohttp. This method converts only the bool values in top-level of a given dict. @@ -28,8 +29,7 @@ def convert_bool_to_0_or_1(params: Optional[Dict[str, Any]]) -> Optional[Dict[st def get_user_agent(prefix: Optional[str] = None, suffix: Optional[str] = None): - """Construct the user-agent header with the package info, - Python version and OS version. + """Construct the user-agent header with the package info, Python version and OS version. Returns: The user agent string. @@ -59,8 +59,7 @@ def _get_url(base_url: str, api_method: str) -> str: def _next_cursor_is_present(data) -> bool: - """Determine if the response contains 'next_cursor' - and 'next_cursor' is not empty. + """Determine if the response contains 'next_cursor' and 'next_cursor' is not empty. Returns: A boolean value. diff --git a/slack_discovery_sdk/proxy_support.py b/slack_discovery_sdk/proxy_support.py index 29f87aa..ad30b3a 100644 --- a/slack_discovery_sdk/proxy_support.py +++ b/slack_discovery_sdk/proxy_support.py @@ -1,6 +1,6 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -"""Internal module for loading proxy-related env variables""" +"""Internal module for loading proxy-related env variables.""" import logging import os diff --git a/slack_discovery_sdk/response.py b/slack_discovery_sdk/response.py index 551361d..5185da1 100644 --- a/slack_discovery_sdk/response.py +++ b/slack_discovery_sdk/response.py @@ -98,6 +98,7 @@ def __getitem__(self, key): def __iter__(self): """Enables the ability to iterate over the response. + It's required for the iterator protocol. Note: From 39dce1b965585bd1b3dde31860f70182cd01f40f Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:54:48 -0500 Subject: [PATCH 5/8] build: add mypy type checking Replace pytype with mypy, using the config and scripts shared with python-slack-sdk, bolt-python, and python-slack-hooks, and a Typecheck CI job. Fix the errors it found: - type the HTTP request helpers and drop the unused type: ignore comments - allow an empty response body in DiscoveryResponse - remove the root __init__.py, which made the repo look like a package - fix the examples package, whose import of a parent module failed Offline tests with a local HTTP server cover the success and error paths of the request code that changed. Co-Authored-By: Claude --- .github/workflows/ci-build.yml | 17 ++++++ .github/workflows/pytype.yml | 34 ----------- __init__.py | 10 --- pyproject.toml | 4 ++ requirements/dev-tools.txt | 4 ++ scripts/install_and_run_tests.sh | 20 ++++++ scripts/run_mypy.sh | 10 +++ slack_discovery_sdk/__init__.py | 1 - slack_discovery_sdk/base_client.py | 61 +++++++++---------- slack_discovery_sdk/client.py | 6 +- .../examples/DLP_call_pattern.py | 4 +- slack_discovery_sdk/examples/__init__.py | 2 - .../examples/audit_logs_pattern.py | 4 +- .../examples/get_enterprise_info.py | 2 +- .../examples/user_based_eDiscovery_pattern.py | 4 +- .../user_based_eDiscovery_with_edits.py | 13 ++-- slack_discovery_sdk/internal_utils.py | 2 +- slack_discovery_sdk/oauth.py | 2 +- slack_discovery_sdk/rate_limit_support.py | 2 +- slack_discovery_sdk/response.py | 15 +++-- tests/test_base_client.py | 53 ++++++++++++++++ 21 files changed, 167 insertions(+), 103 deletions(-) delete mode 100644 .github/workflows/pytype.yml delete mode 100644 __init__.py create mode 100755 scripts/install_and_run_tests.sh create mode 100755 scripts/run_mypy.sh create mode 100644 tests/test_base_client.py diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index c08febd..17af4d4 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -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 diff --git a/.github/workflows/pytype.yml b/.github/workflows/pytype.yml deleted file mode 100644 index e5991a7..0000000 --- a/.github/workflows/pytype.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Type hint validation using pytype - -on: - push: - branches: - - main - pull_request: - -jobs: - build: - runs-on: ubuntu-latest - timeout-minutes: 5 - strategy: - matrix: - python-version: - - "3.9" - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - ./scripts/install.sh - # As pytype can change its behavior in newer versions, we manually upgrade it - pip install "pytype==2023.9.27" - - name: Run pytype - run: | - pytype slack_discovery_sdk/ diff --git a/__init__.py b/__init__.py deleted file mode 100644 index 798f785..0000000 --- a/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -import logging -from logging import NullHandler - -# from .rtm import RTMClient # noqa -from slack_discovery_sdk import DiscoveryClient # noqa - -# Set default logging handler to avoid "No handler found" warnings. -logging.getLogger(__name__).addHandler(NullHandler()) diff --git a/pyproject.toml b/pyproject.toml index 0d28b18..85dad96 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -78,3 +78,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 diff --git a/requirements/dev-tools.txt b/requirements/dev-tools.txt index c8d26c9..83591ec 100644 --- a/requirements/dev-tools.txt +++ b/requirements/dev-tools.txt @@ -2,3 +2,7 @@ # ruff ruff==0.17.4 + +# 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" diff --git a/scripts/install_and_run_tests.sh b/scripts/install_and_run_tests.sh new file mode 100755 index 0000000..2dc7787 --- /dev/null +++ b/scripts/install_and_run_tests.sh @@ -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 +fi diff --git a/scripts/run_mypy.sh b/scripts/run_mypy.sh new file mode 100755 index 0000000..d3c9cde --- /dev/null +++ b/scripts/run_mypy.sh @@ -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 diff --git a/slack_discovery_sdk/__init__.py b/slack_discovery_sdk/__init__.py index 4af1680..cbcea08 100644 --- a/slack_discovery_sdk/__init__.py +++ b/slack_discovery_sdk/__init__.py @@ -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. diff --git a/slack_discovery_sdk/base_client.py b/slack_discovery_sdk/base_client.py index 8120919..bc23d3a 100644 --- a/slack_discovery_sdk/base_client.py +++ b/slack_discovery_sdk/base_client.py @@ -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: @@ -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: @@ -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, @@ -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 @@ -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"]), @@ -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: @@ -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: @@ -303,20 +303,20 @@ 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: @@ -324,21 +324,20 @@ def _perform_urllib_http_request( 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)) @@ -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( @@ -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( @@ -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: diff --git a/slack_discovery_sdk/client.py b/slack_discovery_sdk/client.py index 05dd924..47a22d9 100644 --- a/slack_discovery_sdk/client.py +++ b/slack_discovery_sdk/client.py @@ -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): diff --git a/slack_discovery_sdk/examples/DLP_call_pattern.py b/slack_discovery_sdk/examples/DLP_call_pattern.py index 582588b..d253b71 100644 --- a/slack_discovery_sdk/examples/DLP_call_pattern.py +++ b/slack_discovery_sdk/examples/DLP_call_pattern.py @@ -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) diff --git a/slack_discovery_sdk/examples/__init__.py b/slack_discovery_sdk/examples/__init__.py index 5f7f331..c48c8d4 100644 --- a/slack_discovery_sdk/examples/__init__.py +++ b/slack_discovery_sdk/examples/__init__.py @@ -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 diff --git a/slack_discovery_sdk/examples/audit_logs_pattern.py b/slack_discovery_sdk/examples/audit_logs_pattern.py index 83f2815..93dbe7c 100644 --- a/slack_discovery_sdk/examples/audit_logs_pattern.py +++ b/slack_discovery_sdk/examples/audit_logs_pattern.py @@ -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 diff --git a/slack_discovery_sdk/examples/get_enterprise_info.py b/slack_discovery_sdk/examples/get_enterprise_info.py index cf25a4e..ed10137 100644 --- a/slack_discovery_sdk/examples/get_enterprise_info.py +++ b/slack_discovery_sdk/examples/get_enterprise_info.py @@ -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__) diff --git a/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py b/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py index 52797be..69d63fb 100644 --- a/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py +++ b/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py @@ -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) diff --git a/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py b/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py index e1fe853..435682c 100644 --- a/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py +++ b/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py @@ -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) @@ -41,11 +41,12 @@ # using discovery.conversations.history channel_conversation = client.discovery_conversations_history(channel=channel_id, team=team_id) + history = channel_conversation.body or {} - channel_conversation_json = json.dumps(channel_conversation.body, indent=4) + channel_conversation_json = json.dumps(history, indent=4) # Step 4 - check if the conversation has edits, and if it does, call the conversation.edits endpoint - if channel_conversation.body["has_edits"] is False: + if history["has_edits"] is False: export_json_to_file( new_items=channel_conversation_json, base_dir="./example-outputs/", @@ -56,8 +57,8 @@ else: edits_response = client.discovery_conversations_edits(channel=channel_id, team=team_id) # If has_edits is true, merge the edits into the conversation history file. - channel_conversation.body["edits"] = edits_response["edits"] - edits_response_json = json.dumps(channel_conversation.body, indent=4) + history["edits"] = edits_response["edits"] + edits_response_json = json.dumps(history, indent=4) export_json_to_file( new_items=edits_response_json, base_dir="./example-outputs/", diff --git a/slack_discovery_sdk/internal_utils.py b/slack_discovery_sdk/internal_utils.py index c3e7b73..ca06967 100644 --- a/slack_discovery_sdk/internal_utils.py +++ b/slack_discovery_sdk/internal_utils.py @@ -8,7 +8,7 @@ from typing import Dict, Union, Optional, Any from urllib.parse import urljoin -from .version import __version__ # type:ignore +from .version import __version__ def convert_bool_to_0_or_1(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: diff --git a/slack_discovery_sdk/oauth.py b/slack_discovery_sdk/oauth.py index 78de8b1..b4e2f3e 100644 --- a/slack_discovery_sdk/oauth.py +++ b/slack_discovery_sdk/oauth.py @@ -7,7 +7,7 @@ from http.server import SimpleHTTPRequestHandler, HTTPServer from typing import Dict, Sequence, Union, Optional -from .client import DiscoveryClient # type:ignore +from .client import DiscoveryClient class DiscoveryOAuthApp: diff --git a/slack_discovery_sdk/rate_limit_support.py b/slack_discovery_sdk/rate_limit_support.py index ab62eaf..1bc9218 100644 --- a/slack_discovery_sdk/rate_limit_support.py +++ b/slack_discovery_sdk/rate_limit_support.py @@ -91,7 +91,7 @@ def append_api_call_result(self, api_method: str, is_success: bool): def calculate_sleep_duration(self, api_method: str) -> float: self.cleanup() - sleep_seconds = 0 + sleep_seconds = 0.0 # The estimated count of all the requests performed in the last second last_second_org_call_count = len(self.org_call_histories_in_last_second) * self.number_of_nodes diff --git a/slack_discovery_sdk/response.py b/slack_discovery_sdk/response.py index 5185da1..58a904a 100644 --- a/slack_discovery_sdk/response.py +++ b/slack_discovery_sdk/response.py @@ -3,10 +3,13 @@ """A Python module for interacting and consuming responses from Slack.""" import logging -from typing import Optional +from typing import TYPE_CHECKING, Optional -from .errors import DiscoveryApiError # type:ignore -from .internal_utils import _next_cursor_is_present # type:ignore +from .errors import DiscoveryApiError +from .internal_utils import _next_cursor_is_present + +if TYPE_CHECKING: + from .base_client import BaseDiscoveryClient _LATEST_OFFSET_APIS = [ @@ -53,16 +56,16 @@ class DiscoveryResponse: removed at anytime. """ - def __init__( # type: ignore + def __init__( self, *, - client: "BaseDiscoveryClient", # noqa: F821 + client: "BaseDiscoveryClient", http_method: str, api_url: str, request_headers: dict, request_params: Optional[dict], raw_body: str, - body: dict, + body: Optional[dict], headers: dict, status_code: int, ): diff --git a/tests/test_base_client.py b/tests/test_base_client.py new file mode 100644 index 0000000..bd3d2cc --- /dev/null +++ b/tests/test_base_client.py @@ -0,0 +1,53 @@ +import json +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +import pytest + +from slack_discovery_sdk import DiscoveryClient +from slack_discovery_sdk.errors import DiscoveryApiError + + +class MockHandler(BaseHTTPRequestHandler): + def do_POST(self): + self.respond(200, {"ok": True, "user_id": "U123"}) + + def do_GET(self): + self.respond(500, {"ok": False, "error": "fatal_error"}) + + def respond(self, status, body): + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.end_headers() + self.wfile.write(json.dumps(body).encode("utf-8")) + + def log_message(self, format, *args): + pass + + +@pytest.fixture +def client(): + server = HTTPServer(("localhost", 0), MockHandler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield DiscoveryClient( + token="xoxp-test", + base_url=f"http://localhost:{server.server_port}/api/", + rate_limit_error_prevention_enabled=False, + ) + server.shutdown() + server.server_close() + + +class TestBaseClient: + def test_successful_response(self, client): + response = client.auth_test() + assert response.status_code == 200 + assert response["user_id"] == "U123" + assert response.headers["Content-Type"] == "application/json; charset=utf-8" + + def test_error_response(self, client): + with pytest.raises(DiscoveryApiError) as e: + client.discovery_enterprise_info() + assert e.value.response.status_code == 500 + assert e.value.response["error"] == "fatal_error" From d7343e14494ed881eb76ca61525d5498cc405c8f Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:55:24 -0500 Subject: [PATCH 6/8] ci: add pypi release workflow Publish to PyPI with trusted publishing when a GitHub release is published, and to TestPyPI on a manual run, with the same workflow as python-slack-sdk, bolt-python, and python-slack-hooks. Add the maintainers guide with the release steps and the release notes config, and remove the script that uploaded from a local machine. Co-Authored-By: Claude --- .github/maintainers_guide.md | 232 +++++++++++++++++++++++++++++ .github/release.yml | 24 +++ .github/workflows/pypi-release.yml | 107 +++++++++++++ scripts/deploy_to_prod_pypi_org.sh | 14 -- 4 files changed, 363 insertions(+), 14 deletions(-) create mode 100644 .github/maintainers_guide.md create mode 100644 .github/release.yml create mode 100644 .github/workflows/pypi-release.yml delete mode 100755 scripts/deploy_to_prod_pypi_org.sh diff --git a/.github/maintainers_guide.md b/.github/maintainers_guide.md new file mode 100644 index 0000000..6f2f0f2 --- /dev/null +++ b/.github/maintainers_guide.md @@ -0,0 +1,232 @@ +# Maintainers Guide + +This document describes tools, tasks and workflow that one needs to be familiar with in order to effectively maintain +this project. If you use this package within your own software as is but don't plan on modifying it, this guide is +**not** for you. + +## Tools + +### Python (and friends) + +We recommend using [pyenv](https://github.com/pyenv/pyenv) for Python runtime management. If you use macOS, follow the following steps: + +```sh +brew update +brew install pyenv +``` + +Install necessary Python runtimes for development/testing. You can rely on GitHub Actions for testing with various major versions. + +```sh +pyenv install -l | grep -v "-e[conda|stackless|pypy]" + +pyenv install 3.9.18 # select the latest patch version +pyenv local 3.9.18 + +pyenv versions + system + 3.6.10 + 3.7.7 +* 3.9.18 (set by /path-to-python-slack-discovery-sdk/.python-version) + +pyenv rehash +``` + +Then, you can create a new Virtual Environment this way: + +```sh +python -m venv env_3.9.18 +source env_3.9.18/bin/activate +``` + +## Tasks + +### Testing + +#### Run All the Unit Tests + +If you make some changes to this project, please write corresponding unit tests as much as possible. You can easily run all the tests by running the following scripts. + +If this is your first time to run tests, although it may take a bit longer, running the following script is the easiest. + +```sh +./scripts/install_and_run_tests.sh +``` + +To simply install all the development dependencies for this project. + +```sh +./scripts/install.sh +``` + +Once you installed all the required dependencies, you can use the following. + +```sh +./scripts/run_tests.sh +./scripts/run_tests.sh tests/test_rate_limit_support.py +``` + +Tests marked `live` call the real Discovery API and are skipped unless `SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN` is set. See [Running tests](../README.md#running-tests) for the app and tokens they need. + +To format this project + +```sh +./scripts/format.sh +``` + +To lint this project + +```sh +./scripts/lint.sh +``` + +This project uses [mypy](https://mypy.readthedocs.io/en/stable/index.html) to check and infers types for your Python code. + +```sh +./scripts/run_mypy.sh +``` + +To clean your virtual environment (useful when testing scripts in isolation): + +```sh +./scripts/uninstall_all.sh +``` + +> **Note**: Several scripts support a `--no-install` flag to prevent redundant dependency installation when scripts call other scripts internally. + +#### Develop Locally + +If you want to test the package locally you can. + +1. Build the package locally + + - Run + + ```sh + scripts/build_pypi_package.sh + ``` + + - This will create a `.whl` file in the `./dist` folder + +2. Use the built package + + - Example `/dist/slack_discovery_sdk-1.2.3-py3-none-any.whl` was created + - From anywhere on your machine you can install this package to a project with + + ```sh + pip install /dist/slack_discovery_sdk-1.2.3-py3-none-any.whl + ``` + +### Releasing + +#### test.pypi.org deployment + +[TestPyPI](https://test.pypi.org/) is a separate instance of the Python Package +Index that allows you to try distribution tools and processes without affecting +the real index. This is particularly useful when making changes related to the +package configuration itself, for example, modifications to the `pyproject.toml` file. + +You can deploy this project to TestPyPI using GitHub Actions. + +To deploy using GitHub Actions: + +1. Push your changes to a branch or tag +2. Navigate to +3. Click on "Run workflow" +4. Select your branch or tag from the dropdown +5. Click "Run workflow" to build and deploy your branch to TestPyPI + +Alternatively, you can deploy from your local machine with: + +```sh +./scripts/deploy_to_test_pypi.sh +``` + +#### Development Deployment + +Deploying a new version of this library to PyPI is triggered by publishing a GitHub Release. +Before creating a new release, ensure that everything on a stable branch has +landed, then [run the tests](#run-all-the-unit-tests). + +1. Create the commit for the release + 1. Use the latest supported Python version. Using a [virtual environment](#python-and-friends) is recommended. + 2. In `slack_discovery_sdk/version.py` bump the version number in adherence to [Semantic Versioning](http://semver.org/) and [Developmental Release](https://peps.python.org/pep-0440/#developmental-releases). + - Example: if the current version is `1.2.3`, a proper development bump would be `1.2.4.dev0` + - `.dev` will indicate to pip that this is a [Development Release](https://peps.python.org/pep-0440/#developmental-releases) + - Note that the `dev` version can be bumped in development releases: `1.2.4.dev0` -> `1.2.4.dev1` + 3. Commit with a message including the new version number. For example `1.2.4.dev0` & push the commit to a branch where the development release will live (create it if it does not exist) + 1. `git checkout -b future-release` + 2. `git add --all` (review files with `git status` before committing) + 3. `git commit -m 'chore(release): version 1.2.4.dev0'` + 4. `git push -u origin future-release` +2. Create a new GitHub Release + 1. Navigate to the [Releases page](https://github.com/slackapi/python-slack-discovery-sdk/releases). + 2. Click the "Draft a new release" button. + 3. Set the "Target" to the feature branch with the development changes. + 4. Click "Tag: Select tag" + 5. Input a new tag name manually. The tag name must match the version in `slack_discovery_sdk/version.py` prefixed with "v" (e.g., if version is `1.2.4.dev0`, enter `v1.2.4.dev0`) + 6. Click the "Create a new tag" button. This won't create your tag immediately. + 7. Click the "Generate release notes" button. + 8. The release name should match the tag name! + 9. Edit the resulting notes to ensure they have decent messaging that is understandable by non-contributors, but each commit should still have its own line. + 10. Set this release as a pre-release. + 11. Publish the release by clicking the "Publish release" button! +3. Navigate to the [release workflow run](https://github.com/slackapi/python-slack-discovery-sdk/actions/workflows/pypi-release.yml). You will need to approve the deployment! +4. After a few minutes, the corresponding version will be available on . +5. (Slack Internal) Communicate the release internally + +#### Production Deployment + +Deploying a new version of this library to PyPI is triggered by publishing a GitHub Release. +Before creating a new release, ensure that everything on the `main` branch since +the last tag is in a releasable state! At a minimum, [run the tests](#run-all-the-unit-tests). + +1. Create the commit for the release + 1. Use the latest supported Python version. Using a [virtual environment](#python-and-friends) is recommended. + 2. In `slack_discovery_sdk/version.py` bump the version number in adherence to [Semantic Versioning](http://semver.org/) and the [Versioning](#versioning-and-tags) section. + 3. Commit with a message including the new version number. For example `1.2.3` & push the commit to a branch and create a PR to sanity check. + 1. `git checkout -b 1.2.3-release` + 2. `git add --all` (review files with `git status` before committing) + 3. `git commit -m 'chore(release): version 1.2.3'` + 4. `git push -u origin 1.2.3-release` + 4. Add relevant labels to the PR and add the PR to a GitHub Milestone. + 5. Merge in release PR after getting an approval from at least one maintainer. +2. Create a new GitHub Release + 1. Navigate to the [Releases page](https://github.com/slackapi/python-slack-discovery-sdk/releases). + 2. Click the "Draft a new release" button. + 3. Set the "Target" to the `main` branch. + 4. Click "Tag: Select tag" + 5. Input a new tag name manually. The tag name must match the version in `slack_discovery_sdk/version.py` prefixed with "v" (e.g., if version is `1.2.3`, enter `v1.2.3`) + 6. Click the "Create a new tag" button. This won't create your tag immediately. + 7. Click the "Generate release notes" button. + 8. The release name should match the tag name! + 9. Edit the resulting notes to ensure they have decent messaging that is understandable by non-contributors, but each commit should still have its own line. + 10. Include a link to the current GitHub Milestone. + 11. Ensure the "latest release" checkbox is checked to mark this as the latest stable release. + 12. Publish the release by clicking the "Publish release" button! +3. Navigate to the [release workflow run](https://github.com/slackapi/python-slack-discovery-sdk/actions/workflows/pypi-release.yml). You will need to approve the deployment! +4. After a few minutes, the corresponding version will be available on . +5. Close the current GitHub Milestone and create one for the next patch version. +6. (Slack Internal) Communicate the release internally + - Include a link to the GitHub release +7. (Slack Internal) Tweet by @SlackAPI + - Not necessary for patch updates, might be needed for minor updates, + definitely needed for major updates. Include a link to the GitHub release + +## Workflow + +### Versioning and Tags + +This project uses [Semantic Versioning](http://semver.org/), expressed through the numbering scheme of +[PEP-0440](https://www.python.org/dev/peps/pep-0440/). + +### Branches + +`main` is where active development occurs. Long running named feature branches are occasionally created for +collaboration on a feature that has a large scope (because everyone cannot push commits to another person's open Pull +Request). At some point in the future after a major version increment, there may be maintenance branches for older major +versions. + +## Everything else + +When in doubt, find the other maintainers and ask. diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 0000000..b2574b7 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,24 @@ +# https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes#configuring-automatically-generated-release-notes +changelog: + categories: + - title: ๐Ÿš€ Enhancements + labels: + - enhancement + - title: ๐Ÿ› Bug Fixes + labels: + - bug + - title: ๐Ÿ“š Documentation + labels: + - docs + - title: ๐Ÿค– Build + labels: + - build + - title: ๐Ÿงช Testing/Code Health + labels: + - code health + - title: ๐Ÿ”’ Security + labels: + - security + - title: ๐Ÿ“ฆ Other changes + labels: + - "*" diff --git a/.github/workflows/pypi-release.yml b/.github/workflows/pypi-release.yml new file mode 100644 index 0000000..0aebf76 --- /dev/null +++ b/.github/workflows/pypi-release.yml @@ -0,0 +1,107 @@ +name: Upload A Release to pypi.org or test.pypi.org + +on: + release: + types: + - published + workflow_dispatch: + inputs: + dry_run: + description: "Dry run (build only, do not publish)" + required: false + type: boolean + +jobs: + release-build: + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.release.tag_name || github.ref }} + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.x" + + - name: Build release distributions + run: | + scripts/build_pypi_package.sh + + - name: Persist dist folder + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-dist + path: dist/ + + test-pypi-publish: + runs-on: ubuntu-latest + needs: + - release-build + # Run this job for workflow_dispatch events when dry_run input is not 'true' + # Note: The comparison is against a string value 'true' since GitHub Actions inputs are strings + if: github.event_name == 'workflow_dispatch' && github.event.inputs.dry_run != 'true' + environment: + name: testpypi + permissions: + id-token: write + + steps: + - name: Retrieve dist folder + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: release-dist + path: dist/ + + - name: Publish release distributions to test.pypi.org + # Using OIDC for PyPI publishing (no API tokens needed) + # See: https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-pypi + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + repository-url: https://test.pypi.org/legacy/ + + pypi-publish: + runs-on: ubuntu-latest + needs: + - release-build + if: github.event_name == 'release' + environment: + name: pypi + permissions: + id-token: write + + steps: + - name: Retrieve dist folder + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: release-dist + path: dist/ + + - name: Publish release distributions to pypi.org + # Using OIDC for PyPI publishing (no API tokens needed) + # See: https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-pypi + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + + notify: + if: github.event_name == 'release' && !github.event.release.prerelease && github.repository == 'slackapi/python-slack-discovery-sdk' + runs-on: ubuntu-latest + needs: + - pypi-publish + permissions: + contents: read + + steps: + - name: Notify Slack + uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0 + with: + errors: true + webhook: ${{ secrets.SLACK_RELEASE_ANNOUNCEMENTS_WEBHOOK_URL }} + webhook-type: webhook-trigger + payload: | + action_url: "${{ github.event.release.html_url }}" + message: "python-slack-discovery-sdk ${{ github.event.release.tag_name }}" + repository: "${{ github.repository }}" diff --git a/scripts/deploy_to_prod_pypi_org.sh b/scripts/deploy_to_prod_pypi_org.sh deleted file mode 100755 index a473f72..0000000 --- a/scripts/deploy_to_prod_pypi_org.sh +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -#!/bin/bash - -script_dir=`dirname $0` -cd ${script_dir}/.. -rm -rf ./slack_discovery_sdk.egg-info - -pip install -U pip && \ - pip install twine wheel && \ - rm -rf dist/ build/ slack_discovery_sdk.egg-info/ && \ - python setup.py sdist bdist_wheel && \ - twine check dist/* && \ - twine upload dist/* \ No newline at end of file From 4dad4a3ab0302a57db8abf3dff68ae0c5ec565aa Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 14:06:53 -0500 Subject: [PATCH 7/8] build: use pep 639 license metadata and drop pypy The license is now an SPDX expression with LICENSE.md as its license file. This needs setuptools 77 or newer, which runs on Python 3.9+, so the package is built on the latest Python. The py3-none-any wheel still installs on 3.7+. Because of this, the unit test jobs and install.sh no longer install the package (that would build it on 3.7/3.8). The tests import it from source, as in python-slack-sdk. MANIFEST.in is dropped: setuptools already ships README.md, LICENSE.md, and py.typed. PyPy is dropped from the classifiers and the test matrix since it isn't tested. Co-Authored-By: Claude --- .github/workflows/ci-build.yml | 2 -- MANIFEST.in | 1 - pyproject.toml | 7 +++---- scripts/install.sh | 1 - 4 files changed, 3 insertions(+), 8 deletions(-) delete mode 100644 MANIFEST.in diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 938ce38..120a4f1 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -30,7 +30,6 @@ jobs: - "3.13" - "3.14" - "3.15" - - "pypy3.10" permissions: contents: read steps: @@ -44,7 +43,6 @@ jobs: - name: Install dependencies run: | pip install -U pip - pip install -e . pip install -r requirements/testing.txt - name: Run tests run: | diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index bdd0a11..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1 +0,0 @@ -include README.md LICENSE.md slack_discovery_sdk/py.typed diff --git a/pyproject.toml b/pyproject.toml index a288ac6..ec82611 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,12 +1,13 @@ [build-system] -requires = ["setuptools"] +requires = ["setuptools>=77"] build-backend = "setuptools.build_meta" [project] name = "slack-discovery-sdk" dynamic = ["version", "readme"] description = "The Slack Discovery API SDK for Python" -license = { text = "MIT" } +license = "MIT" +license-files = ["LICENSE.md"] authors = [{ name = "Slack Technologies, LLC", email = "opensource@slack.com" }] requires-python = ">=3.7" dependencies = [] @@ -15,7 +16,6 @@ classifiers = [ "Intended Audience :: Developers", "Topic :: Communications :: Chat", "Topic :: Office/Business", - "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.7", @@ -28,7 +28,6 @@ classifiers = [ "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", ] diff --git a/scripts/install.sh b/scripts/install.sh index bb50709..8150c3c 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -3,5 +3,4 @@ script_dir=$(dirname $0) cd ${script_dir}/.. pip install -U pip -pip install -e . pip install -r requirements/testing.txt From c4824aacbcc57938d0c45c27afffa1133f99b634 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Tue, 17 Nov 2026 15:13:46 -0500 Subject: [PATCH 8/8] build: tidy config left over from the pyproject, ruff, and mypy moves Drop the asyncio deprecation filters carried over from pytest.ini (the package has no async code), collapse the D100-D107 ignores into D1, remove the .pytype/ ignore now that pytype is gone, and merge a split typing import. Co-Authored-By: Claude --- .gitignore | 1 - pyproject.toml | 13 +------------ slack_discovery_sdk/base_client.py | 3 +-- 3 files changed, 2 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index 1dcf449..d85c493 100644 --- a/.gitignore +++ b/.gitignore @@ -41,7 +41,6 @@ tmp.txt .DS_Store logs/ -.pytype/ *.db .env* diff --git a/pyproject.toml b/pyproject.toml index e3f2f61..31d8507 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,14 +50,7 @@ line-length = 125 select = ["E", "W", "F", "D"] ignore = [ # missing-docstring: do not add docstrings where none exist - "D100", - "D101", - "D102", - "D103", - "D104", - "D105", - "D106", - "D107", + "D1", ] [tool.ruff.lint.pydocstyle] @@ -73,10 +66,6 @@ log_file_level = "DEBUG" log_format = "%(asctime)s %(levelname)s %(message)s" log_date_format = "%Y-%m-%d %H:%M:%S" markers = ["live: calls the real Discovery API and needs the SLACK_DISCOVERY_SDK_TEST_* env variables"] -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/" diff --git a/slack_discovery_sdk/base_client.py b/slack_discovery_sdk/base_client.py index bc23d3a..c5144d5 100644 --- a/slack_discovery_sdk/base_client.py +++ b/slack_discovery_sdk/base_client.py @@ -10,8 +10,7 @@ from http.client import HTTPResponse from logging import Logger from ssl import SSLContext -from typing import Any, Dict -from typing import Optional +from typing import Any, Dict, Optional from urllib.error import HTTPError from urllib.parse import urlencode from urllib.request import Request, urlopen, OpenerDirector, ProxyHandler, HTTPSHandler