diff --git a/.github/workflows/cancel-superseded-live-runs.yml b/.github/workflows/cancel-superseded-live-runs.yml new file mode 100644 index 00000000..90af3205 --- /dev/null +++ b/.github/workflows/cancel-superseded-live-runs.yml @@ -0,0 +1,64 @@ +name: Cancel superseded live runs + +# Companion of live-integration.yml. When a pull request gets a new push, this workflow cancels the older "Live tests" +# runs of the same pull request, so a quick fix does not wait for a run that is already out of date. +# +# Why a separate workflow: live-integration.yml has one concurrency group for all pull requests (the jobs of two runs +# must never interleave on the shared keysets), and it never cancels in progress, because that would also cancel the +# run of another pull request. A run that waits for that group cannot run any step, so it cannot cancel anything +# itself. This workflow has no such lock and runs at once. +# +# A cancelled live run still runs its "Revoke grants and clean up" step, and the next run starts with its own janitor +# pass, so cancelling is safe. Only runs of the same pull request with a different head commit are cancelled. Runs of +# other pull requests are never touched. Pull requests from forks have no live jobs and are skipped. + +on: + pull_request: + branches: + - master + types: [opened, synchronize, reopened, ready_for_review] + +permissions: + actions: write + contents: read + +jobs: + cancel: + name: Cancel older live runs of this pull request + if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} + runs-on: + group: organization/Default + timeout-minutes: 5 + steps: + - name: Cancel runs for older commits + uses: actions/github-script@v7 + with: + script: | + const { owner, repo } = context.repo; + const pr = context.payload.pull_request; + const headSha = pr.head.sha; + let cancelled = 0; + for (const status of ['queued', 'in_progress', 'waiting', 'pending']) { + const runs = await github.paginate(github.rest.actions.listWorkflowRuns, { + owner, + repo, + workflow_id: 'live-integration.yml', + event: 'pull_request', + branch: pr.head.ref, + status, + per_page: 100, + }); + for (const run of runs) { + const samePullRequest = (run.pull_requests || []).some((item) => item.number === pr.number); + if (!samePullRequest || run.head_sha === headSha) continue; + core.info(`Cancelling run ${run.id} (${status}, commit ${run.head_sha.slice(0, 8)}) of pull request #${pr.number}`); + try { + await github.rest.actions.cancelWorkflowRun({ owner, repo, run_id: run.id }); + cancelled += 1; + } catch (error) { + // The run may have finished between the list and the cancel. + core.warning(`Could not cancel run ${run.id}: ${error.message}`); + } + } + } + core.info(`Cancelled ${cancelled} older run(s).`); diff --git a/.github/workflows/live-integration.yml b/.github/workflows/live-integration.yml new file mode 100644 index 00000000..eb4c5286 --- /dev/null +++ b/.github/workflows/live-integration.yml @@ -0,0 +1,193 @@ +name: Live tests + +# Live tier (tests/live/README.md): the public documentation's Python and asyncio code samples, run against the real +# PubNub service. Runs on non-draft pull requests into master, and on demand. No scheduled runs. Draft pull requests +# run nothing. Fork pull requests never get the live jobs (no secrets for fork code). +# +# One job per API group. The groups and their files are in tests/live/groups.py. The offline job turns that file into +# the job matrix, so a new group needs no change here except the `group` input options below (the lint checks that +# they match). The matrix runs one group at a time (max-parallel: 1) and does not stop at a failed group +# (fail-fast: false), so every group reports its own result and the run is red when any group failed. Each group checks +# out, installs, cleans the keysets before and after its tests, and can be re-run alone ("Re-run job" on that group). +# +# Without a GitHub Environment with required reviewers, anyone with push access can read the secrets through a pull +# request. This workflow does not set one. + +on: + # Every pull request into master, whatever files it changes, so SDK changes are tested too. A new push to the pull + # request starts a new run. Marking a draft as ready for review also starts a run. + pull_request: + branches: + - master + types: [opened, synchronize, reopened, ready_for_review] + workflow_dispatch: + inputs: + group: + description: 'Run only this group (tests/live/groups.py). "all" runs every group, one after another.' + required: false + default: 'all' + type: choice + # Must list 'all' and then every group name of groups.py, in that order (checked by tests/live/cli.py lint). + options: + - all + - messaging + - getting-started + - app-context + - access-manager + - access-manager-application-level + grep: + description: 'Run only tests whose name matches this pytest -k expression, inside the selected groups. Empty runs everything.' + required: false + default: '' + type: string + +# One live run at a time for the whole workflow: the tier uses fixed resource names on shared keysets, so the jobs of +# two runs must never interleave. This group never cancels in progress, because that would also cancel the run of +# another pull request. A new push to a pull request cancels the older live runs of the same pull request through +# cancel-superseded-live-runs.yml (a run that waits for this group cannot cancel itself). Runs that get no live jobs +# (draft or fork pull requests) take one group per pull request and cancel their own older run. +concurrency: + group: ${{ (github.event_name == 'pull_request' && (github.event.pull_request.draft || github.event.pull_request.head.repo.full_name != github.repository)) && format('python-live-tests-no-live-{0}', github.ref) || 'python-docs-snippets-live' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' && (github.event.pull_request.draft || github.event.pull_request.head.repo.full_name != github.repository) }} + +defaults: + run: + shell: bash + +permissions: + contents: read + +jobs: + compat: + name: Compile and lint (Python ${{ matrix.python }}) + if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} + runs-on: + group: organization/Default + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + python: ["3.9", "3.10", "3.11", "3.12"] + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Setup Python ${{ matrix.python }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - name: Install dependencies + run: pip install -r requirements-dev.txt + - name: Compile the tier + run: python -m compileall -q tests/live + - name: Lint (markers, self-test, manifest, groups, resources) + run: python -u tests/live/cli.py lint + + offline: + name: Offline checks (lint, ruff, collect, plan) + if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} + runs-on: + group: organization/Default + timeout-minutes: 15 + outputs: + matrix: ${{ steps.plan.outputs.matrix }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Setup Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: Install dependencies + run: pip install -r requirements-dev.txt + - name: Compile the tier + run: python -m compileall -q tests/live + - name: Lint (markers, self-test, manifest, groups, resources) + run: python -u tests/live/cli.py lint + - name: Ruff of the tier + run: ruff check tests/live + # No keys and no network: pytest-socket refuses every connection that is not to the loopback address. + - name: Collect without keys or network + working-directory: tests/live + run: python -u -m pytest --collect-only -q --allow-hosts=127.0.0.1,::1 + - name: Plan the group jobs + id: plan + env: + # Empty on pull requests: every group. Reaches the script only through the environment. + GROUP: ${{ inputs.group }} + run: | + matrix="$(python -u tests/live/cli.py groups --matrix "${GROUP:-all}")" + echo "matrix=$matrix" >> "$GITHUB_OUTPUT" + echo "$matrix" + + live: + name: ${{ matrix.group }} + needs: [offline, compat] + # Pull requests: only non-draft ones from a branch of this repository (never a fork: no secrets for fork code). + if: ${{ github.event_name != 'pull_request' || (!github.event.pull_request.draft && github.event.pull_request.head.repo.full_name == github.repository) }} + runs-on: + group: organization/Default + timeout-minutes: 30 + strategy: + # One group at a time (the keysets are shared), and every group runs even after a failed one. + max-parallel: 1 + fail-fast: false + matrix: ${{ fromJSON(needs.offline.outputs.matrix) }} + env: + # Not secrets. Set on the job because they are only keyset ids for the Admin API feature check. + DOCS_SNIPPETS_OPEN_KEYSET_ID: ${{ vars.SDK_DOCS_OPEN_KEYSET_ID }} + DOCS_SNIPPETS_PAM_KEYSET_ID: ${{ vars.SDK_DOCS_PAM_KEYSET_ID }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Setup Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + # Secrets are set per step below, never on the job, so installing dependencies never sees them. + - name: Install dependencies + id: install + run: pip install -r requirements-dev.txt + # Every docs keyset, whatever the group: the janitor cleans every role before and after the group, so each job + # starts and ends clean even when the job before it failed. The role check and the preflight cover only the + # group's roles. + - name: Docs samples (janitor and preflight on) + id: samples + if: ${{ !cancelled() && steps.install.outcome == 'success' && matrix.tier == 'docs' }} + working-directory: tests/live + env: + SUBSCRIBE_KEY: ${{ secrets.SDK_DOCS_OPEN_SUBSCRIBE_KEY }} + PUBLISH_KEY: ${{ secrets.SDK_DOCS_OPEN_PUBLISH_KEY }} + PAM_SUBSCRIBE_KEY: ${{ secrets.SDK_DOCS_PAM_SUBSCRIBE_KEY }} + PAM_PUBLISH_KEY: ${{ secrets.SDK_DOCS_PAM_PUBLISH_KEY }} + PAM_SECRET_KEY: ${{ secrets.SDK_DOCS_PAM_SECRET_KEY }} + PUBNUB_ADMIN_API_KEY: ${{ secrets.SDK_DOCS_ADMIN_API_KEY }} + LIVE_GROUP: ${{ matrix.group }} + # Untrusted input: reaches the script only through the environment. + GREP: ${{ inputs.grep }} + run: | + if [ -n "$GREP" ]; then + python -u -m pytest -k "$GREP" + else + python -u -m pytest + fi + # After a failure or a cancel the tier's own session teardown may not have run (killed process): revoke the + # application-level Access Manager grant and remove leftovers, so a keyset is never left open until the next + # group or run. Docs tier only. + - name: Revoke grants and clean up + if: ${{ (cancelled() || failure()) && steps.install.outcome == 'success' && matrix.tier == 'docs' }} + env: + SUBSCRIBE_KEY: ${{ secrets.SDK_DOCS_OPEN_SUBSCRIBE_KEY }} + PUBLISH_KEY: ${{ secrets.SDK_DOCS_OPEN_PUBLISH_KEY }} + PAM_SUBSCRIBE_KEY: ${{ secrets.SDK_DOCS_PAM_SUBSCRIBE_KEY }} + PAM_PUBLISH_KEY: ${{ secrets.SDK_DOCS_PAM_PUBLISH_KEY }} + PAM_SECRET_KEY: ${{ secrets.SDK_DOCS_PAM_SECRET_KEY }} + run: python -u tests/live/cli.py janitor + # No artifact upload: the tier prints to stdout only and writes no report file. + + # No failure alerts (Slack or similar): the run logs in GitHub are the only signal. diff --git a/.gitignore b/.gitignore index ae82a593..5ae7f970 100644 --- a/.gitignore +++ b/.gitignore @@ -83,3 +83,6 @@ PubNubTwisted.ipynb venv/ reports/ + +# Live tier (tests/live/README.md). Keys only, never commit. +tests/live/.env.local diff --git a/requirements-dev.txt b/requirements-dev.txt index 6d601b1e..904414d6 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -4,6 +4,8 @@ pycryptodomex>=3.21.0 ruff==0.17.* pytest>=8.3.5 pytest-asyncio>=1.0.0 +pytest-socket>=0.7 +pytest-timeout>=2.3 httpx>=0.28 h2>=4.3 requests>=2.32.2 diff --git a/scripts/run-tests.py b/scripts/run-tests.py index ccd216c2..d1b92c3c 100755 --- a/scripts/run-tests.py +++ b/scripts/run-tests.py @@ -11,7 +11,7 @@ REPO_ROOT = _dname(_dname(os.path.abspath(__file__))) os.chdir(os.path.join(REPO_ROOT)) -tcmn = 'py.test tests --cov=pubnub --ignore=tests/manual/' +tcmn = 'py.test tests --cov=pubnub --ignore=tests/manual/ --ignore=tests/live/' fcmn = 'ruff check .' diff --git a/tests/conftest.py b/tests/conftest.py index 4379a080..ac6a180c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,26 @@ +import os + import pytest +# The live tier (tests/live/) has its own pytest.ini and needs keys and the real service. The root run never collects +# it (scripts/run-tests.py also passes --ignore=tests/live/). +collect_ignore = ["live"] + +# Offline guard. PN_OFFLINE_GUARD=1 refuses every connection that is not to the loopback address, through +# pytest-socket (requirements-dev.txt). A test that reaches the real network then fails with SocketConnectBlockedError. +# It is opt-in, because some tests in tests/ use the real network. Same effect: +# py.test tests --allow-hosts=127.0.0.1,::1 +_OFFLINE = os.environ.get("PN_OFFLINE_GUARD") == "1" + + +def pytest_collection_modifyitems(config, items): + if not _OFFLINE: + return + if not config.pluginmanager.hasplugin("socket"): + raise pytest.UsageError("PN_OFFLINE_GUARD=1 needs pytest-socket (pip install -r requirements-dev.txt)") + for item in items: + item.add_marker(pytest.mark.allow_hosts(["127.0.0.1", "::1"])) + @pytest.fixture() def file_upload_test_data(): diff --git a/tests/live/.env.example b/tests/live/.env.example new file mode 100644 index 00000000..dd060a2f --- /dev/null +++ b/tests/live/.env.example @@ -0,0 +1,22 @@ +# Copy to tests/live/.env.local and fill in. Never commit .env.local (it is git-ignored). +# Real environment variables win over this file. LIVE_ENV_FILE= reads another file instead. + +# Open keyset: no Access Manager. Message Persistence with Delete-From-History, Presence, App Context, Files, +# Mobile Push, Stream Controller with wildcard subscribe. +PUBLISH_KEY= +SUBSCRIBE_KEY= + +# Access Manager keyset: Access Manager with token revocation, Message Persistence, Presence. +PAM_PUBLISH_KEY= +PAM_SUBSCRIBE_KEY= +PAM_SECRET_KEY= + +# Optional, read only: the preflight reads the keyset features through the Admin API. +PUBNUB_ADMIN_API_KEY= +DOCS_SNIPPETS_OPEN_KEYSET_ID= +DOCS_SNIPPETS_PAM_KEYSET_ID= + +# Optional switches: off skips the cleanup or the feature check (single-page runs). +# LIVE_JANITOR=off +# LIVE_PREFLIGHT=off +# LIVE_GROUP=messaging diff --git a/tests/live/README.md b/tests/live/README.md new file mode 100644 index 00000000..5a03c7ac --- /dev/null +++ b/tests/live/README.md @@ -0,0 +1,158 @@ +# Live tier: docs samples against the real service + +These tests run the code samples of the Python and asyncio SDK docs against the real PubNub service. Each test checks that its sample does what the docs page says. The docs pages embed the samples straight from these test files, so a sample that is published is a sample that runs. + +A mocked test never runs the docs code and never talks to the service, so it cannot find a wrong docs sample. The other tests in `tests/` check request shape against recorded cassettes. This tier checks what the service does. + +## Layout + +| Path | Purpose | +| :-- | :-- | +| `sync/api_reference/test_.py` | One file per docs page of the sync `PubNub` client. The docs embed these files | +| `asyncio/api_reference/test_.py` | The same pages for `PubNubAsyncio` | +| `shared/.py` | Scenario data per page: the literal resource names (`NAMES`) and the helpers both docsets call outside the markers | +| `support/` | Support package: env and keys, clients, cleanup, waits, janitor, preflight, lint, manifest, groups, docs-check | +| `groups.py` | API groups (data only). One group is one CI job | +| `coverage.json` | Generated manifest, one entry per snippet id per file | +| `snippet-exceptions.json` | Hand-kept list of embeds that are not run and of pages that exist in one docset only, each with a reason | +| `fixtures/` | Files the samples upload | +| `cli.py` | Command line of the tier (`python -u tests/live/cli.py` with no command prints the usage) | +| `.env.example` | Env names. Copy to `.env.local` (git-ignored) | + +`sync/` and `asyncio/` have no `__init__.py` on purpose, so `asyncio/` can never shadow the standard library module. + +## Groups + +`groups.py` splits the test files into API groups. Every test file belongs to exactly one group. An entry can also be a `::` node id that takes one test out of the group that lists its file. Each group lists the keyset roles its tests need. + +| Group | Roles | Pages | +| :-- | :-- | :-- | +| `messaging` | `open` | publish, subscribe, subscribe-legacy, presence, channel groups, message persistence, message-persistence-legacy, message actions, file sharing, mobile push | +| `getting-started` | `open`, `pam` | configuration, encryption, misc | +| `app-context` | `open` | App Context (sync only) | +| `access-manager` | `open`, `pam` | access manager, access-manager-legacy, access-manager-v2 | +| `access-manager-application-level` | `pam` | the application level grant of access-manager-v2 (`test_grant_subkey_all`, sync and asyncio) | + +The order of the list is the order of the serial CI run. `access-manager-application-level` runs last, because its tests open the whole `pam` keyset for a moment and a downgrade is not guaranteed to apply at once. + +## Keys + +| Role | Env names | Keyset features | +| :-- | :-- | :-- | +| `open` | `PUBLISH_KEY`, `SUBSCRIBE_KEY` | Message Persistence with Delete-From-History, Presence with a tracking rule on `*`, App Context with user, channel and membership events and referential integrity off, Files, Mobile Push, Stream Controller with wildcard subscribe, no Access Manager | +| `pam` | `PAM_PUBLISH_KEY`, `PAM_SUBSCRIBE_KEY`, `PAM_SECRET_KEY` | Access Manager with token revocation, Message Persistence with Delete-From-History (the janitor needs it), Presence | +| preflight (optional) | `PUBNUB_ADMIN_API_KEY`, `DOCS_SNIPPETS_OPEN_KEYSET_ID`, `DOCS_SNIPPETS_PAM_KEYSET_ID` | Read only Admin API feature check | + +Real env vars win over `tests/live/.env.local` (or the file in `LIVE_ENV_FILE`). The loader never falls back to demo keys and prints only `set` or `missing` (`python -u tests/live/cli.py env`). + +A full run needs every role. A group run needs the roles of its group. A run narrowed with `-k`, `-m` or file arguments needs the roles of the selected tests, read from `coverage.json`. A missing role stops the run before the first test, with the names of the missing env vars. + +## Run it + +Python 3.9 or later and the dev requirements (`pip install -r requirements-dev.txt`). The tier imports `pubnub` from this checkout. Run pytest from this folder, because pytest applies `testpaths` only when it runs in its rootdir (from the repository root, `-c tests/live/pytest.ini` alone collects the whole repository). + +```bash +python -u tests/live/cli.py lint # offline checks, no keys, no network +cd tests/live +python -u -m pytest --collect-only -q --allow-hosts=127.0.0.1,::1 # no keys, no network +python -u -m pytest # the whole tier: needs both roles +LIVE_GROUP=messaging python -u -m pytest # one group +LIVE_JANITOR=off python -u -m pytest -k publish # one page, without the full cleanup +python -u cli.py janitor # cleanup alone +python -u cli.py preflight # keyset feature check alone +``` + +`LIVE_JANITOR=off` and `LIVE_PREFLIGHT=off` skip those steps. Check `gh run list --workflow live-integration.yml --repo pubnub/python` first: the tier uses fixed names on shared keysets, so a local run on the same keysets collides with a CI run. + +The tier refuses `python -O` (it strips the `assert` statements), `pytest-rerunfailures` (retries hide real failures) and `skip`, `skipif` or `xfail` marks. Each test has a 120 s timeout. A test that needs more carries `@pytest.mark.timeout(n)`. + +## How a test is written + +A test is a `test_*` function. The docs sample sits between `# snippet.` and `# snippet.end` inside the test body, with the literal names the docs show. Client setup and every assertion sit outside the markers. The first paragraph of the docstring names the snippet ids. + +```python +def test_signal_message(clients): + """Snippet: signal_message.""" + pubnub = clients.sync('open', 'signaler') + seen = listen(clients.sync('open', 'subscriber'), 'my_channel') + + # snippet.signal_message + envelope = pubnub.signal() \ + .channel("my_channel") \ + .message("typing_on") \ + .sync() + # snippet.end + + a.timetoken(envelope.result.timetoken) + eventually(lambda: a.eq([s.message for s in seen.signals], ['typing_on'])) +``` + +The docs embed the region with `EmbeddedCode` from `https://raw.githubusercontent.com/pubnub/python/refs/heads/master/tests/live//api_reference/test_.py` and `snippets={['signal_message']}`. The docs extractor removes the common indentation. Nothing is staged or rewritten. + +What may be inside the snippet region: + +* The sample code exactly as the docs page shows it, with the literal resource names of the page. +* Keys on one hidden line between `# snippet.hide` and `# snippet.show`. A hidden block holds at most 3 lines of code and is never published. + +What may not be inside the snippet region: + +* Assertions, `pytest`, the waits (`eventually`, `settled`, `connected` and the like) or any name imported from `support` or `shared`. +* `try`/`except`, `traceback` or `logging.exception`, unless the purpose of the sample is the error handling the page shows (allow-list `ERROR_HANDLING_SNIPPETS`). +* A `return` of the function that holds the snippet. + +The marker lint (`support/lint_markers.py`) enforces these rules and lists them all. In short: + +* Marker syntax is `# snippet.` with a space after `#`. The docs extractor ignores `#snippet.x`. +* An id appears once per docset folder, because the docs address a snippet by file and id. +* The visible text compiles on its own (`await` is allowed in asyncio files). +* Every test asserts after each snippet's end line. +* asyncio: `await ....future()` returns an error object instead of raising, so every envelope a snippet binds is checked by an assertion after the end line (rule P1). +* A whole-file sample (a `.py` file under a docset folder that is not `test_*.py`) is run by a test that names it. + +A sample that cannot run against the service goes in a function decorated with `@compile_only(reason)` (`support/marks.py`). pytest does not collect it, but the file is imported, so the sample still compiles, and the manifest lists it as compile-only. + +Fixtures: `clients` hands out sync clients (`clients.sync('open', 'user')`, `clients.sync('pam', 'admin')`), `aclients` asyncio clients (`aclients.asyncio(...)`). Both stop every client after the test. `support.cleanup.cleanup_after_test(label, fn)` registers a removal that runs after the test body, before the clients stop. Use `eventually()` for a read that must succeed once, `settled()` for a read after a write that must succeed several times in a row (a lagging replica), and `sleep()` only to prove that something does not happen. + +## Checks + +All of these run offline, without keys or network. + +| Command | What it checks | +| :-- | :-- | +| `cli.py lint` | Compiles the tier, runs the marker lint, the lint self-test (broken fixtures, redaction, extractor cases), `manifest --check`, `groups --check`, the shape of `snippet-exceptions.json` and the shape of the resource names | +| `cli.py manifest` | Writes `coverage.json` from the markers. `--check` fails when the file is stale. Never edit it by hand | +| `cli.py groups --check` | Every test file in exactly one group, every listed file and test exists, every role a file uses is in its group, and the workflow `group` input lists `all` and then every group name in order | +| `cli.py docs-check ` | Classifies every `EmbeddedCode` from `pubnub/python` in `docs/sdks/python/` and `docs/sdks/asyncio/` as live, compile-only, exception or NOT COVERED. `--report-only` never fails, `--allow-ref ` accepts a docs preview branch in the URL | +| `cli.py parity` | Snippet ids that exist in one docset only, per page | +| `cli.py extractor --regen ` | Regenerates `support/extractor_fixtures.json` with the docs extractor itself (`npx tsx`), so the self-test can compare the Python copy of the extractor against it | + +`snippet-exceptions.json` is hand-kept. `exceptions` lists docs embeds that no test runs, each with a path, optional ids and a reason. `one_sided` lists pages that exist in one docset only, each with a reason. The lint checks the shape and `docs-check` reads the exceptions. + +## Cleanup + +The tests use the names the docs show, so the names are fixed, shared and persistent. `support/resources.py` and the `NAMES` list of each `shared/.py` list every name the tier uses. The lint fails on a name with a run suffix. + +* Janitor (`support/janitor.py`): before and after every run, it cleans exactly the listed names on every role that has keys (history and files of a channel, channel groups, App Context users and channels and their memberships, push devices) and revokes the application-level Access Manager (v2) grant. It never sweeps by name pattern and never lists a keyset. A failed cleanup before the run stops the run. A failed revoke after the run fails it. +* Grant check: when the run uses the `pam` role, the janitor waits until a client without a token is refused on the `pam` keyset again. +* Preflight (`support/preflight.py`): before the first test it names every keyset feature a role lacks, through the Admin API (with `PUBNUB_ADMIN_API_KEY` and the keyset ids) and through live probes on the `open` keyset. +* Per test: the registered cleanups run after the test body. Then the client fixtures unsubscribe and stop every client and send an explicit leave for every channel and group a client was still subscribed to, so a client that stays an occupant never hides the join event of the same user ID from the next test. Helper clients use a short presence timeout for the same reason. +* After the run: a check that no non-daemon thread is left. + +## CI + +`.github/workflows/live-integration.yml` runs on every non-draft pull request into `master` and on dispatch (inputs `group` and `grep`). There is no schedule. Fork pull requests never get the live jobs. + +1. `compat`: compile and `cli.py lint` on Python 3.9 to 3.12. +2. `offline`: compile, `cli.py lint`, Ruff of the tier, a collect without keys or network, and the job matrix from `groups.py` (`cli.py groups --matrix`). +3. `live`: one job per group, one at a time, without stopping at a failed group. After a failure or a cancel, a last step runs `cli.py janitor` so a keyset is never left open. + +One live run at a time runs for the whole workflow, because the keysets are shared. `cancel-superseded-live-runs.yml` cancels older runs of the same pull request when it gets a new push. The run logs in GitHub are the only failure signal. + +## Add a page + +1. Write `sync/api_reference/test_.py` and `asyncio/api_reference/test_.py`, one test per sample or group of samples, with the markers and assertions as above. +2. Put the resource names of the page in `NAMES` of `shared/.py`, with the helpers both docsets call. A coroutine twin of a sync helper carries an `_async` suffix. +3. Add both files to a group in `groups.py`. A new group also needs its name in the `group` input options of the workflow. +4. Run `python -u tests/live/cli.py manifest`, then `cli.py lint` and Ruff (`ruff check tests/live`, configured by the `ruff.toml` of the repository). +5. Run the page live (`python -u -m pytest -k ` from `tests/live`). +6. Point the docs `EmbeddedCode` tags at the file and ids, and run `cli.py docs-check `. A page that exists in one docset only goes in `one_sided` of `snippet-exceptions.json`. diff --git a/tests/live/asyncio/api_reference/test_access_manager.py b/tests/live/asyncio/api_reference/test_access_manager.py new file mode 100644 index 00000000..40d54f88 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_access_manager.py @@ -0,0 +1,254 @@ +"""Docs page: access-manager (asyncio), Access Manager v3 tokens. Same steps as sync/access_manager.py with await. + +The asyncio client does not raise on an HTTP or validation error. future() resolves with a PubNubAsyncioException +object instead, so the helpers below inspect the resolved value. +""" +from pubnub.models.consumer.v3.channel import Channel +import pytest + +from support import assertions as a +from support import redact +from support.wait import aeventually +from shared.access_manager import ( + allowed_async as allowed, failure, holder_async as holder, perms, refused_async as refused, +) + + +async def test_grant_token_builder(aclients): + """Snippets: grant_token_builder, parse_token.""" + pubnub = aclients.asyncio('pam', 'admin') + + # snippet.grant_token_builder + from pubnub.models.consumer.v3.channel import Channel + + envelope = await pubnub.grant_token() \ + .channels([ + Channel.id('readonly-channel').read(), + Channel.id('readwrite-channel').read().write(), + ]) \ + .authorized_uuid("my-authorized-uuid") \ + .ttl(15) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + token = envelope.result.token + redact.register(token) + a.ok(isinstance(token, str) and len(token) > 40, 'the result carries a token') + a.eq(envelope.result.get_token(), token) + + # snippet.parse_token + parsed_token = pubnub.parse_token(token) + # snippet.end + + a.eq(parsed_token['version'], 2) + a.eq(parsed_token['ttl'], 15) + a.eq(parsed_token['authorized_uuid'], 'my-authorized-uuid') + a.eq(parsed_token['resources']['channels'], { + 'readonly-channel': perms('read'), + 'readwrite-channel': perms('read', 'write'), + }) + a.eq(parsed_token['resources'].get('groups', {}), {}) + a.eq(parsed_token['resources'].get('uuids', {}), {}) + a.eq(parsed_token['patterns'].get('channels', {}), {}) + a.ok('categories' not in parsed_token, 'no category in a token granted without categories') + + +async def test_set_token(aclients): + """Snippet: set_token.""" + admin = aclients.asyncio('pam', 'admin') + readonly = 'readonly-channel' + readwrite = 'readwrite-channel' + fresh = 'set_token_other_channel' + granted = await admin.grant_token() \ + .channels([Channel.id(readonly).read(), Channel.id(readwrite).read().write()]) \ + .authorized_uuid('my-authorized-uuid') \ + .ttl(15) \ + .future() + token = granted.result.token + redact.register(token) + without = holder(aclients, 'my-authorized-uuid') + pubnub = holder(aclients, 'my-authorized-uuid') + + # snippet.set_token + pubnub.set_token(token) + # snippet.end + + await aeventually(lambda: allowed(pubnub, readwrite), timeout=30, what='publish on the granted channel') + await refused(pubnub, readonly) + await refused(pubnub, fresh) + await refused(without, readwrite) + + +@pytest.mark.timeout(240) +async def test_revoke_token(aclients): + """Snippet: revoke_token.""" + admin = aclients.asyncio('pam', 'admin') + pubnub = admin + channel = 'revoke-channel' + granted = await admin.grant_token() \ + .channels([Channel.id(channel).read().write()]) \ + .authorized_uuid('my-authorized-uuid') \ + .ttl(15) \ + .future() + token = granted.result.token + redact.register(token) + holder_client = holder(aclients, 'my-authorized-uuid', token) + await aeventually(lambda: allowed(holder_client, channel), timeout=30, what='publish with the fresh token') + + # A client without a secret key cannot revoke. The SDK refuses before it sends the request. + keyless = holder(aclients, 'my-authorized-uuid') + a.contains(failure(await keyless.revoke_token(token).future()), 'Secret key is not configured') + + # snippet.revoke_token + envelope = await pubnub.revoke_token(token).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + + a.eq(envelope.result.status, 200) + a.eq(str(envelope.result), 'Revoke token success with status: 200') + await aeventually(lambda: refused(holder_client, channel), timeout=100, interval=2, + what='the revoked token is refused') + for number in (1, 2): + await refused(holder(aclients, 'my-authorized-uuid', token), channel) + + +async def test_grant_token_categories(aclients): + """Snippets: grant_token_categories, parse_token_categories.""" + pubnub = aclients.asyncio('pam', 'admin') + + # snippet.grant_token_categories + from pubnub.models.consumer.v3.category import Category + + envelope = await pubnub.grant_token( + categories=[Category.channels().get(), Category.uuids().get()], + authorized_user_id='my_authorized_uuid', + ttl=15 + ).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + token = envelope.result.get_token() + # snippet.end + redact.register(token) + + # snippet.parse_token_categories + categories = pubnub.parse_token(token)['categories'] + # snippet.end + + a.eq(categories, {'channels': {'get': True}, 'uuids': {'get': True}}) + parsed = pubnub.parse_token(token) + a.eq(parsed['authorized_uuid'], 'my_authorized_uuid') + a.eq(parsed['resources'].get('channels', {}), {}) + a.eq(parsed['resources'].get('uuids', {}), {}) + + # A token with a single category carries only that category. + single = await pubnub.grant_token().categories([Category.channels().get()]).ttl(15).future() + redact.register(single.result.token) + a.eq(pubnub.parse_token(single.result.token)['categories'], {'channels': {'get': True}}) + + # The SDK refuses an invalid category before it sends the request. + resolved = await pubnub.grant_token().categories([Channel.id('x').get()]).ttl(15).future() + a.contains(failure(resolved), 'Unsupported category. Only Category.channels() and Category.uuids() are supported') + resolved = await pubnub.grant_token().categories([Category.channels()]).ttl(15).future() + a.contains(failure(resolved), "Category permissions must be exactly the 'get' permission") + + +async def test_grant_token_multi(aclients): + """Snippets: grant_token_multi, grant_token_regex, grant_token_multi_regex.""" + pubnub = aclients.asyncio('pam', 'admin') + authorized = 'my-authorized-uuid' + + # snippet.grant_token_multi + from pubnub.models.consumer.v3.channel import Channel + from pubnub.models.consumer.v3.group import Group + from pubnub.models.consumer.v3.uuid import UUID + + channels = [ + Channel.id("channel-a").read(), + Channel.id("channel-b").read().write(), + Channel.id("channel-c").read().write(), + Channel.id("channel-d").read().write() + ] + groups = [ + Group.id("channel-group-b").read() + ] + uuids = [ + UUID.id("uuid-c").get(), + UUID.id("uuid-d").get().update() + ] + envelope = await pubnub.grant_token() \ + .channels(channels) \ + .groups(groups) \ + .ttl(15) \ + .uuids(uuids) \ + .authorized_uuid("my-authorized-uuid") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + parsed = pubnub.parse_token(envelope.result.token) + redact.register(envelope.result.token) + a.eq(parsed['authorized_uuid'], authorized) + a.eq(parsed['resources']['channels'], { + 'channel-a': perms('read'), + 'channel-b': perms('read', 'write'), + 'channel-c': perms('read', 'write'), + 'channel-d': perms('read', 'write'), + }) + a.eq(parsed['resources']['groups'], {'channel-group-b': perms('read')}) + a.eq(parsed['resources']['uuids'], {'uuid-c': perms('get'), 'uuid-d': perms('get', 'update')}) + a.eq(parsed['patterns'].get('channels', {}), {}) + + # snippet.grant_token_regex + from pubnub.models.consumer.v3.channel import Channel + + envelope = await pubnub.grant_token() \ + .channels([Channel.pattern("channel-[A-Za-z0-9]").read()]) \ + .ttl(15) \ + .authorized_uuid("my-authorized-uuid") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + parsed = pubnub.parse_token(envelope.result.token) + redact.register(envelope.result.token) + a.eq(parsed['patterns']['channels'], {'channel-[A-Za-z0-9]': perms('read')}) + a.eq(parsed['resources'].get('channels', {}), {}) + + # snippet.grant_token_multi_regex + from pubnub.models.consumer.v3.channel import Channel + from pubnub.models.consumer.v3.group import Group + from pubnub.models.consumer.v3.uuid import UUID + + channels = [ + Channel.id("channel-a").read(), + Channel.pattern("channel-[A-Za-z0-9]").read(), + Channel.id("channel-b").read().write(), + Channel.id("channel-c").read().write(), + Channel.id("channel-d").read().write() + ] + groups = [ + Group.id("channel-group-b").read() + ] + uuids = [ + UUID.id("uuid-c").get(), + UUID.id("uuid-d").get().update() + ] + envelope = await pubnub.grant_token() \ + .channels(channels) \ + .ttl(15) \ + .groups(groups) \ + .uuids(uuids) \ + .authorized_uuid("my-authorized-uuid") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + parsed = pubnub.parse_token(envelope.result.token) + redact.register(envelope.result.token) + a.eq(parsed['patterns']['channels'], {'channel-[A-Za-z0-9]': perms('read')}) + a.eq(sorted(parsed['resources']['channels']), ['channel-a', 'channel-b', 'channel-c', 'channel-d']) + a.eq(parsed['resources']['groups'], {'channel-group-b': perms('read')}) + a.eq(parsed['resources']['uuids'], {'uuid-c': perms('get'), 'uuid-d': perms('get', 'update')}) diff --git a/tests/live/asyncio/api_reference/test_access_manager_legacy.py b/tests/live/asyncio/api_reference/test_access_manager_legacy.py new file mode 100644 index 00000000..d6313e05 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_access_manager_legacy.py @@ -0,0 +1,114 @@ +"""Docs page: access-manager-legacy (asyncio). The samples of the legacy page.""" +from support import assertions as a +from support import redact +from shared.access_manager import perms + + +async def test_grant_token_spaces_builder(aclients): + """Snippets: grant_token_spaces_builder, grant_token_spaces_multi, grant_token_spaces_regex, + grant_token_spaces_multi_regex.""" + pubnub = aclients.asyncio('pam', 'admin') + + # snippet.grant_token_spaces_builder + from pubnub.models.consumer.v3.space import Space + from pubnub.models.consumer.v3.user import User + + envelope = await pubnub.grant_token() \ + .spaces([ + Space.id("my_space").read().write().manage(), + ]) \ + .users([ + User.id("my_user").get().update(), + ]) \ + .ttl(15) \ + .authorized_user("my-authorized-userId") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + token = envelope.result.token + # snippet.end + redact.register(token) + parsed = pubnub.parse_token(token) + a.eq(parsed['ttl'], 15) + a.eq(parsed['authorized_uuid'], 'my-authorized-userId') + a.eq(parsed['resources']['channels'], {'my_space': perms('read', 'write', 'manage')}) + a.eq(parsed['resources']['uuids'], {'my_user': perms('get', 'update')}) + + # snippet.grant_token_spaces_multi + from pubnub.models.consumer.v3.space import Space + from pubnub.models.consumer.v3.user import User + + spaces = [ + Space.id("space-a").read(), + Space.id("space-b").read().write(), + Space.id("space-c").read().write(), + Space.id("space-d").read().write() + ] + users = [ + User.id("userId-c").get(), + User.id("userId-d").get().update() + ] + envelope = await pubnub.grant_token() \ + .spaces(spaces) \ + .ttl(15) \ + .users(users) \ + .authorized_user("my-authorized-userId") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + parsed = pubnub.parse_token(envelope.result.token) + redact.register(envelope.result.token) + a.eq(parsed['resources']['channels'], { + 'space-a': perms('read'), + 'space-b': perms('read', 'write'), + 'space-c': perms('read', 'write'), + 'space-d': perms('read', 'write'), + }) + a.eq(parsed['resources']['uuids'], {'userId-c': perms('get'), 'userId-d': perms('get', 'update')}) + + # snippet.grant_token_spaces_regex + from pubnub.models.consumer.v3.space import Space + + envelope = await pubnub.grant_token() \ + .spaces([Space.pattern("space-[A-Za-z0-9]").read()]) \ + .ttl(15) \ + .authorized_user("my-authorized-userId") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + parsed = pubnub.parse_token(envelope.result.token) + redact.register(envelope.result.token) + a.eq(parsed['patterns']['channels'], {'space-[A-Za-z0-9]': perms('read')}) + + # snippet.grant_token_spaces_multi_regex + from pubnub.models.consumer.v3.space import Space + from pubnub.models.consumer.v3.user import User + + spaces = [ + Space.id("space-a").read(), + Space.pattern("space-[A-Za-z0-9]").read(), + Space.id("space-b").read().write(), + Space.id("space-c").read().write(), + Space.id("space-d").read().write() + ] + users = [ + User.id("user-c").get(), + User.id("user-d").get().update() + ] + envelope = await pubnub.grant_token() \ + .spaces(spaces) \ + .ttl(15) \ + .users(users) \ + .authorized_user("my-authorized-userId") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + parsed = pubnub.parse_token(envelope.result.token) + redact.register(envelope.result.token) + a.eq(parsed['patterns']['channels'], {'space-[A-Za-z0-9]': perms('read')}) + a.eq(sorted(parsed['resources']['channels']), ['space-a', 'space-b', 'space-c', 'space-d']) + a.eq(parsed['resources']['uuids'], {'user-c': perms('get'), 'user-d': perms('get', 'update')}) diff --git a/tests/live/asyncio/api_reference/test_access_manager_v2.py b/tests/live/asyncio/api_reference/test_access_manager_v2.py new file mode 100644 index 00000000..5e7c9859 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_access_manager_v2.py @@ -0,0 +1,314 @@ +"""Docs page: access-manager-v2 (asyncio), the legacy grant(). Same steps as sync/access_manager_v2.py with await. + +Every grant is closed in a finally (all flags false, ttl 1). The step that grants at application level is the last one +of this file. The asyncio client does not raise on an HTTP error, future() resolves with a PubNubAsyncioException. + +The application level grant (test_grant_subkey_all) runs in its own group, access-manager-application-level, the +last one in groups.py. A downgrade is not asserted to apply at once. future() resolves with an exception object on +failure, so the result type is asserted instead of a try/except. +""" +from pubnub.exceptions import PubNubAsyncioException +import pytest + +from support import assertions as a +from support.listen import alisten +from support.wait import aeventually +from shared.access_manager_v2 import ( + accepted, allowed_async as allowed, close_application_level_async as close_application_level, + close_grant_async as close_grant, failure, good, holder_async as holder, key_flags, refused_async as refused, +) + + +async def test_grant_channel_auth(aclients): + """Snippet: grant_channel_auth.""" + pubnub = aclients.asyncio('pam', 'admin') + channels = [name for name in ('ch1', 'ch2', 'ch3')] + groups = [name for name in ('cg1', 'cg2')] + other = 'ch_no_grant' + try: + # snippet.grant_channel_auth + envelope = await pubnub.grant().channels(["ch1", "ch2", "ch3"]).\ + channel_groups(["cg1", "cg2"]).\ + auth_keys(["key1", "key2"]).\ + read(True).write(True).manage(True).\ + future() + # snippet.end + + result = good(envelope) + a.eq(result.level, 'channel-group+auth') + a.eq(result.ttl, 1440) + a.ok(isinstance(result.subscribe_key, str) and result.subscribe_key, 'the result names the subscribe key') + a.eq(sorted(result.channels), sorted(channels)) + a.eq(sorted(result.groups), sorted(groups)) + for data in list(result.channels.values()) + list(result.groups.values()): + a.eq(sorted(data.auth_keys), ['key1', 'key2']) + for key_data in data.auth_keys.values(): + a.eq(key_flags(key_data)[:3], (True, True, True)) + await aeventually(lambda: allowed(holder(aclients, 'granted', 'key1'), channels[0]), timeout=30, + what='a granted auth key publishes') + await refused(holder(aclients, 'stranger', 'key3'), channels[0]) + await refused(holder(aclients, 'granted', 'key1'), other) + finally: + await close_grant(pubnub, channels, groups, auth_keys=['key1', 'key2']) + + +async def test_grant_channel_all_users(aclients): + """Snippets: grant_channel_all_users, grant_channel_level.""" + pubnub = aclients.asyncio('pam', 'admin') + channel = 'my_channel' + other = 'ch_no_grant' + try: + # snippet.grant_channel_all_users + envelope = await pubnub.grant().channels("my_channel").read(True).write(True).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + + result = good(envelope) + a.eq(result.level, 'channel') + a.eq(result.ttl, 1440) + a.eq((result.channels[channel].read_enabled, result.channels[channel].write_enabled), (True, True)) + client = holder(aclients, 'anyone') + await aeventually(lambda: allowed(client, channel), timeout=30, what='publish without an auth key') + await refused(client, other) + + # snippet.grant_channel_level + envelope = await pubnub.grant().channels("my_channel"). \ + read(True).write(True). \ + future() + # snippet.end + + result = good(envelope) + a.eq(result.level, 'channel') + a.eq(result.channels[channel].read_enabled, True) + finally: + await close_grant(pubnub, [channel]) + + +@pytest.mark.timeout(900) +async def test_grant_channel_ro_auth(aclients): + """Snippets: grant_channel_ro_auth, grant_user_level.""" + pubnub = aclients.asyncio('pam', 'admin') + channel = 'my_channel' + other = 'ch_no_grant' + try: + # snippet.grant_channel_ro_auth + envelope = await pubnub.grant().channels("my_channel").read(True).write(False).\ + auth_keys("my_ro_authkey").ttl(5).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + + result = good(envelope) + a.eq(result.level, 'user') + a.eq(result.ttl, 5) + a.eq(list(result.channels), [channel]) + a.eq(list(result.channels[channel].auth_keys), ['my_ro_authkey']) + key_data = result.channels[channel].auth_keys['my_ro_authkey'] + a.eq((key_data.read_enabled, key_data.write_enabled), (True, False)) + reader = holder(aclients, 'reader', 'my_ro_authkey') + # The read grant is proved by a subscribe that connects. The missing write grant by a refused publish. + await alisten(reader, channel) + await aeventually(lambda: refused(reader, channel), timeout=300, + what='reader write refused, a channel level downgrade can take minutes') + await aeventually(lambda: refused(holder(aclients, 'stranger', 'other_authkey'), channel), timeout=300, + what='a stranger auth key refused, a channel level downgrade can take minutes') + finally: + await close_grant(pubnub, [channel], auth_keys=['my_ro_authkey']) + + try: + # snippet.grant_user_level + envelope = await pubnub.grant().channels("my_channel"). \ + auth_keys("my_authkey"). \ + read(True).write(True). \ + ttl(5). \ + future() + # snippet.end + + result = good(envelope) + a.eq(result.level, 'user') + a.eq(key_flags(result.channels[channel].auth_keys['my_authkey'])[:2], (True, True)) + await aeventually(lambda: allowed(holder(aclients, 'writer', 'my_authkey'), channel), timeout=30, + what='publish with the granted auth key') + await aeventually(lambda: refused(holder(aclients, 'writer', 'my_authkey'), other), timeout=300, + what='a channel without a grant refused, a channel level downgrade can take minutes') + finally: + await close_grant(pubnub, [channel], auth_keys=['my_authkey']) + + +async def test_grant_presence(aclients): + """Snippet: grant_presence.""" + pubnub = aclients.asyncio('pam', 'admin') + presence = 'my_channel-pnpres' + try: + # snippet.grant_presence + envelope = await pubnub.grant(). \ + channels("my_channel-pnpres").read(True).write(True).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + + result = good(envelope) + a.eq(result.level, 'channel') + a.eq(list(result.channels), [presence]) + a.eq((result.channels[presence].read_enabled, result.channels[presence].write_enabled), (True, True)) + client = holder(aclients, 'presence_reader') + + async def here_now_not_refused(): + resolved = await client.here_now().channels(presence).future() + a.ok(not isinstance(resolved, PubNubAsyncioException), 'here_now on the presence channel was refused') + + await aeventually(here_now_not_refused, timeout=30, what='here_now on the presence channel') + finally: + await close_grant(pubnub, [presence]) + + +async def test_grant_channel_group(aclients): + """Snippet: grant_channel_group.""" + pubnub = aclients.asyncio('pam', 'admin') + groups = [name for name in ('cg1', 'cg2', 'cg3')] + member = 'group_member' + try: + # snippet.grant_channel_group + envelope = await pubnub.grant(). \ + channel_groups(["cg1", "cg2", "cg3"]). \ + auth_keys(["auth1", "auth2", "auth3"]). \ + read(True).write(True).manage(True). \ + ttl(12237). \ + future() + # snippet.end + + result = good(envelope) + a.eq(result.level, 'channel-group+auth') + a.eq(result.ttl, 12237) + a.eq(sorted(result.groups), sorted(groups)) + for data in result.groups.values(): + a.eq(sorted(data.auth_keys), ['auth1', 'auth2', 'auth3']) + for key_data in data.auth_keys.values(): + a.eq(key_flags(key_data)[:3], (True, True, True)) + manager = holder(aclients, 'group_manager', 'auth1') + + async def add_member(): + resolved = await manager.add_channel_to_channel_group().channels(member).channel_group(groups[0]).future() + a.ok(not isinstance(resolved, PubNubAsyncioException), 'the manage grant lets the auth key edit the group') + + await aeventually(add_member, timeout=30, what='the manage grant lets the auth key edit the group') + listed = good(await pubnub.list_channels_in_channel_group().channel_group(groups[0]).future()) + a.eq(list(listed.channels), [member]) + resolved = await holder(aclients, 'stranger', 'auth9').add_channel_to_channel_group() \ + .channels(member).channel_group(groups[1]).future() + a.ok(isinstance(resolved, PubNubAsyncioException), 'an auth key without a grant is refused') + a.eq(resolved.status.status_code, 403) + finally: + try: + await pubnub.remove_channel_group().channel_group(groups[0]).future() + finally: + await close_grant(pubnub, groups=groups, auth_keys=['auth1', 'auth2', 'auth3']) + + +async def test_grant_multiple_channels(aclients): + """Snippet: grant_multiple_channels.""" + pubnub = aclients.asyncio('pam', 'admin') + channels = ['girish', 'girish2'] + try: + # snippet.grant_multiple_channels + envelope = await pubnub.grant().\ + auth_keys("my_rw_authkey").\ + channels(["girish", "girish2"]).\ + read(True).\ + write(True).\ + ttl(5).\ + future() + # snippet.end + + result = good(envelope) + a.eq(result.level, 'user') + a.eq(result.ttl, 5) + a.eq(sorted(result.channels), sorted(channels)) + for data in result.channels.values(): + a.eq(list(data.auth_keys), ['my_rw_authkey']) + a.eq(key_flags(data.auth_keys['my_rw_authkey'])[:2], (True, True)) + client = holder(aclients, 'rw', 'my_rw_authkey') + for channel in channels: + await aeventually(lambda: allowed(client, channel), timeout=30, what='publish on a granted channel') + finally: + await close_grant(pubnub, channels, auth_keys=['my_rw_authkey']) + + +async def test_grant_categories(aclients): + """Snippet: grant_categories.""" + pubnub = aclients.asyncio('pam', 'admin') + auth_key = 'my_auth_key' + try: + # snippet.grant_categories + envelope = await pubnub.grant() \ + .auth_keys(auth_key) \ + .categories(['channels', 'uuids']) \ + .get(True) \ + .ttl(15) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + print(f"Granted category permissions, level: {envelope.result.level}") + # snippet.end + + result = good(envelope) + a.eq(result.level, 'category') + a.eq(result.ttl, 15) + a.eq(sorted(result.categories), ['channels', 'uuids']) + for name, data in result.categories.items(): + a.eq(data.name, name) + a.eq(list(data.auth_keys), [auth_key]) + a.eq(data.auth_keys[auth_key].get, True) + a.eq(data.auth_keys[auth_key].read_enabled, False) + closed = good(await pubnub.grant().auth_keys(auth_key).categories(['channels']).get(False).future()) + a.eq(closed.categories['channels'].auth_keys[auth_key].get, False) + finally: + await pubnub.grant().auth_keys(auth_key).categories(['channels', 'uuids']).get(False).future() + + # The SDK refuses these before it sends the request. + a.contains(failure(await pubnub.grant().auth_keys(auth_key).categories(['groups']).get(True).ttl(15).future()), + "Unsupported categories: groups. Only 'channels' and 'uuids' are supported") + a.contains(failure(await pubnub.grant().categories(['channels']).get(True).ttl(15).future()), + 'Category grants require providing non empty authKeys') + a.contains(failure(await pubnub.grant().auth_keys(auth_key).categories(['channels']).read(True).get(True) + .ttl(15).future()), + "Category grants allow only the 'get' permission") + a.contains(failure(await pubnub.grant().auth_keys(auth_key).categories(['channels']).get(True).ttl(1).future()), + 'One-minute (ttl=1) category grants are not supported') + + +@pytest.mark.timeout(300) +async def test_grant_subkey_all(aclients): + """Snippets: grant_subkey_all, grant_application_level.""" + pubnub = aclients.asyncio('pam', 'admin') + try: + # snippet.grant_subkey_all + envelope = await pubnub.grant().read(True).write(True).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + + result = accepted(envelope) + a.eq(result.level, 'subkey') + a.eq(result.ttl, 1440) + a.eq((result.read_enabled, result.write_enabled), (True, True)) + finally: + closed = await close_application_level(pubnub) + + try: + # snippet.grant_application_level + envelope = await pubnub.grant(). \ + read(True).write(True). \ + future() + # snippet.end + + result = accepted(envelope) + a.eq(result.level, 'subkey') + a.eq((result.read_enabled, result.write_enabled), (True, True)) + finally: + closed = await close_application_level(pubnub) + result = accepted(closed) + a.eq(result.level, 'subkey') + a.eq((result.read_enabled, result.write_enabled), (False, False)) diff --git a/tests/live/asyncio/api_reference/test_channel_groups.py b/tests/live/asyncio/api_reference/test_channel_groups.py new file mode 100644 index 00000000..46962fc7 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_channel_groups.py @@ -0,0 +1,147 @@ +"""Docs page: channel groups (asyncio). Same steps as sync/channel_groups.py with await. + +Every step registers its group with the janitor and deletes it in a finally. +""" +from support import assertions as a +from support import cleanup as live_cleanup +from support.listen import alisten +from support.wait import aeventually +from shared.channel_groups import eventually_members_async as eventually_members, members_async as members + + +async def test_add_channels_builder(aclients): + """Snippets: add_channels_builder, add_channels_named.""" + pubnub = aclients.asyncio('open', 'grouper') + group = 'cg1' + channels = ['ch1', 'ch2'] + live_cleanup.record('channel_group', group) + try: + # snippet.add_channels_builder + envelope = await pubnub.add_channel_to_channel_group() \ + .channels(["ch1", "ch2"]) \ + .channel_group("cg1") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.status.is_error(), False) + a.eq(str(envelope.result), 'Channel successfully added') + await eventually_members(pubnub, group, channels) + + # A subscriber on the group receives a publish to a member channel + seen = await alisten(aclients.asyncio('open', 'member_listener'), groups=[group]) + await pubnub.publish().channel(channels[0]).message('to-member').future() + await aeventually(lambda: a.eq([m.message for m in seen.messages], ['to-member'], 'group message received')) + a.eq((seen.messages[0].channel, seen.messages[0].subscription), (channels[0], group)) + + await pubnub.remove_channel_from_channel_group().channels(channels).channel_group(group).future() + await eventually_members(pubnub, group, []) + + # snippet.add_channels_named + envelope = await pubnub.add_channel_to_channel_group(channels=["ch1", "ch2"], channel_group="cg1").future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.status.is_error(), False) + await eventually_members(pubnub, group, channels) + finally: + await pubnub.remove_channel_group().channel_group(group).future() + + +async def test_list_channels_builder(aclients): + """Snippets: list_channels_builder, list_channels_named.""" + pubnub = aclients.asyncio('open', 'lister') + group = 'cg1' + channels = ['ch1', 'ch2'] + live_cleanup.record('channel_group', group) + try: + await pubnub.add_channel_to_channel_group().channels(channels).channel_group(group).future() + await eventually_members(pubnub, group, channels) + + # snippet.list_channels_builder + envelope = await pubnub.list_channels_in_channel_group() \ + .channel_group("cg1") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + print(envelope.result.channels) + # snippet.end + a.eq(sorted(envelope.result.channels), channels) + a.eq(type(envelope.result.channels), list, 'channels is a list, not a dictionary') + + # snippet.list_channels_named + envelope = await pubnub.list_channels_in_channel_group(channel_group="cg1").future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(sorted(envelope.result.channels), channels) + a.eq(await members(pubnub, 'missing_group'), [], 'an unknown group is empty') + finally: + await pubnub.remove_channel_group().channel_group(group).future() + + +async def test_remove_channels_builder(aclients): + """Snippets: remove_channels_builder, remove_channels_named.""" + pubnub = aclients.asyncio('open', 'remover') + group = 'channel_group' + kids = ['son', 'daughter'] + pair = ['ch1', 'ch2'] + other_group = 'cg1' + live_cleanup.record('channel_group', group) + live_cleanup.record('channel_group', other_group) + try: + await pubnub.add_channel_to_channel_group().channels(kids + pair).channel_group(group).future() + await pubnub.add_channel_to_channel_group().channels(pair).channel_group(other_group).future() + await eventually_members(pubnub, group, kids + pair) + + # snippet.remove_channels_builder + envelope = await pubnub.remove_channel_from_channel_group() \ + .channels(["son", "daughter"]) \ + .channel_group("channel_group") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.status.is_error(), False) + a.eq(str(envelope.result), 'Channel successfully removed') + await eventually_members(pubnub, group, pair) + + # snippet.remove_channels_named + envelope = await pubnub.remove_channel_from_channel_group(channels=["ch1", "ch2"], + channel_group="cg1").future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.status.is_error(), False) + await eventually_members(pubnub, other_group, []) + a.eq(await members(pubnub, group), sorted(pair), 'the other group is untouched') + finally: + await pubnub.remove_channel_group().channel_group(group).future() + await pubnub.remove_channel_group().channel_group(other_group).future() + + +async def test_delete_channel_group_builder(aclients): + """Snippet: delete_channel_group_builder.""" + pubnub = aclients.asyncio('open', 'deleter') + group = 'cg1' + channels = ['ch1', 'ch2'] + live_cleanup.record('channel_group', group) + try: + await pubnub.add_channel_to_channel_group().channels(channels).channel_group(group).future() + await eventually_members(pubnub, group, channels) + + # snippet.delete_channel_group_builder + envelope = await pubnub.remove_channel_group() \ + .channel_group("cg1") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.status.is_error(), False) + a.eq(str(envelope.result), 'Group successfully removed') + await eventually_members(pubnub, group, []) + # The docs show remove_channel_group(channel_group="cg1"), but the method takes no argument + a.raises(TypeError, lambda: pubnub.remove_channel_group(channel_group=group)) + finally: + await pubnub.remove_channel_group().channel_group(group).future() diff --git a/tests/live/asyncio/api_reference/test_configuration.py b/tests/live/asyncio/api_reference/test_configuration.py new file mode 100644 index 00000000..8e851275 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_configuration.py @@ -0,0 +1,294 @@ +"""Docs page: configuration (asyncio). Source: docs/sdks/asyncio/api-reference/configuration.md. + +The initialization samples use made up keys, so each step overwrites the keys on the same config object after the +sample ran and then proves the client works against the service. Validation branches replace the network call of the +request handler with a counter, so they prove that no request was sent. +""" +import asyncio +import re +from os import environ +from unittest import mock + +from pubnub.pubnub_asyncio import AsyncioSubscriptionManager, PubNubAsyncio +from pubnub.request_handlers.async_httpx import AsyncHttpxRequestHandler + +from support import assertions as a +from support.clients import config as client_config +from support.listen import alisten +from support.wait import aeventually +from shared.configuration import ( + RequestCounter_async as RequestCounter, UNREACHABLE, USER_ID_ERROR, real_keys, works_async as works, +) + + +async def test_configuration_full(aclients): + """Snippet: configuration_full.""" + real = client_config('open') + saved = {k: environ.get(k) for k in ('PUBNUB_SUBSCRIBE_KEY', 'PUBNUB_PUBLISH_KEY', 'PUBNUB_USER_ID')} + environ.update({'PUBNUB_SUBSCRIBE_KEY': real.subscribe_key, 'PUBNUB_PUBLISH_KEY': real.publish_key, + 'PUBNUB_USER_ID': 'configured_user'}) + try: + # snippet.configuration_full + import os + from pubnub.pnconfiguration import PNConfiguration + from pubnub.enums import PNHeartbeatNotificationOptions + from pubnub.pubnub_asyncio import PubNubAsyncio + + # Configuration for the client instance + pn_configuration = PNConfiguration() + + # Set configuration values + pn_configuration.subscribe_key = os.getenv('PUBNUB_SUBSCRIBE_KEY', 'demo') # required + pn_configuration.publish_key = os.getenv('PUBNUB_PUBLISH_KEY', 'demo') # only required if publishing + pn_configuration.secret_key = os.getenv('PUBNUB_SECRET_KEY', 'my_secret_key') # optional + pn_configuration.user_id = os.getenv('PUBNUB_USER_ID', 'my_custom_user_id') # must be set + pn_configuration.auth_key = os.getenv('PUBNUB_AUTH_KEY', 'my_auth_key') # optional + pn_configuration.ssl = True + pn_configuration.filter_expression = "such == 'wow'" + pn_configuration.heartbeat_notification_options = PNHeartbeatNotificationOptions.ALL + + # Adding the requested parameters + pn_configuration.enable_subscribe = True # required if you want to subscribe + pn_configuration.enable_presence_heartbeat = True # sends presence heartbeats for subscribed channels + + # The configuration is ready to pass to PubNub + # Simply create a PubNub instance using it: + pubnub = PubNubAsyncio(pn_configuration) + + print("Configuration set up complete.") + # snippet.end + finally: + for key, value in saved.items(): + if value is None: + environ.pop(key, None) + else: + environ[key] = value + aclients._made.append(pubnub) + a.eq(pn_configuration.subscribe_key, real.subscribe_key, 'keys come from the environment') + a.eq(pubnub.uuid, 'configured_user') + a.eq(pn_configuration.heartbeat_notification_options, PNHeartbeatNotificationOptions.ALL) + a.eq((pn_configuration.enable_subscribe, pn_configuration.enable_presence_heartbeat), (True, True)) + a.eq((pn_configuration.auth_key, pn_configuration.filter_expression), ('my_auth_key', "such == 'wow'")) + + # The configured client publishes, and a plain client on the same channel reads the message + channel = 'my_channel' + seen = await alisten(aclients.asyncio('open', 'config_reader'), channel) + envelope = await pubnub.publish().channel(channel).message({'configured': True}).future() + a.timetoken(envelope.result.timetoken) + + async def received(): + a.eq([m.message for m in seen.messages], [{'configured': True}], 'reader received') + await aeventually(received) + + +async def test_initialize_pubnub(aclients): + """Snippets: initialize_pubnub, initialize_non_secure, initialize_ssl, initialize_custom_user_id.""" + # snippet.initialize_pubnub + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio + + pnconfig = PNConfiguration() + pnconfig.subscribe_key = "my_subkey" + pnconfig.publish_key = "my_pubkey" + pnconfig.ssl = True + pnconfig.user_id = "my_custom_user_id" + pubnub = PubNubAsyncio(pnconfig) + # snippet.end + a.eq((pubnub.uuid, pnconfig.ssl), ('my_custom_user_id', True)) + a.ok((await works(aclients, pubnub, pnconfig)).status.tls_enabled, 'requests use TLS') + + # snippet.initialize_non_secure + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio + + pnconfig = PNConfiguration() + pnconfig.subscribe_key = "my_subkey" + pnconfig.publish_key = "my_pubkey" + pnconfig.ssl = False + pnconfig.user_id = "my_custom_user_id" + pubnub = PubNubAsyncio(pnconfig) + # snippet.end + a.eq(pnconfig.scheme(), 'http') + a.eq((await works(aclients, pubnub, pnconfig)).status.tls_enabled, False, 'requests are plain http') + + # snippet.initialize_ssl + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio + + pnconfig = PNConfiguration() + pnconfig.subscribe_key = "my_subkey" + pnconfig.publish_key = "my_pubkey" + pnconfig.ssl = True + pnconfig.user_id = "my_custom_user_id" + pubnub = PubNubAsyncio(pnconfig) + # snippet.end + a.eq(pnconfig.scheme_and_host(), 'https://ps.pndsn.com') + a.ok((await works(aclients, pubnub, pnconfig)).status.tls_enabled, 'requests use TLS') + + # snippet.initialize_custom_user_id + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio + + pnconfig = PNConfiguration() + + pnconfig.subscribe_key = 'mySubscribeKey' + pnconfig.publish_key = 'myPublishKey' + pnconfig.user_id = "my_custom_user_id" + + pubnub = PubNubAsyncio(pnconfig) + # snippet.end + a.eq(pubnub.uuid, 'my_custom_user_id') + a.eq(pnconfig.user_id, pnconfig.uuid, 'user_id and the deprecated uuid are the same value') + await works(aclients, pubnub, pnconfig) + + # The user ID is mandatory. The branches below never reach the network. + counter = RequestCounter() + with mock.patch.object(AsyncHttpxRequestHandler, '_request_with_wall_clock_deadline', counter): + missing = PNConfiguration() + missing.subscribe_key = 'mySubscribeKey' + missing.origin = UNREACHABLE + a.raises(AssertionError, PubNubAsyncio, missing, match=re.escape(USER_ID_ERROR)) + for bad in ('', ' ', None, 42): + a.raises(AssertionError, setattr, missing, 'user_id', bad, match=re.escape(USER_ID_ERROR)) + a.eq(missing.user_id, None, 'a rejected user_id is not stored') + a.eq(counter.calls, 0, 'no request was sent') + + +async def test_initialize_custom_request_handler(aclients): + """Snippet: initialize_custom_request_handler.""" + # snippet.initialize_custom_request_handler + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio + from pubnub.request_handlers.async_aiohttp import AsyncAiohttpRequestHandler + + pnconfig = PNConfiguration() + pnconfig.subscribe_key = "my_subkey" + pnconfig.publish_key = "my_pubkey" + pnconfig.ssl = True + pnconfig.user_id = "my_custom_user_id" + pubnub = PubNubAsyncio(pnconfig, custom_request_handler=AsyncAiohttpRequestHandler) + # snippet.end + a.ok(isinstance(pubnub._request_handler, AsyncAiohttpRequestHandler), 'the custom handler is in use') + a.ok(not isinstance(pubnub._request_handler, AsyncHttpxRequestHandler), 'the default handler is replaced') + await works(aclients, pubnub, pnconfig) + a.raises(Exception, PubNubAsyncio, pnconfig, custom_request_handler=dict, match='subclass of BaseRequestHandler') + + +async def test_initialize_read_only(aclients): + """Snippet: initialize_read_only.""" + channel = 'my_channel' + + # snippet.initialize_read_only + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio + + pnconfig = PNConfiguration() + pnconfig.subscribe_key = "my_subkey" + pnconfig.user_id = "my_custom_user_id" + + pubnub = PubNubAsyncio(pnconfig) + # snippet.end + aclients._made.append(pubnub) + a.eq(pnconfig.publish_key, None, 'no publish key') + + counter = RequestCounter() + pnconfig.origin = UNREACHABLE + with mock.patch.object(AsyncHttpxRequestHandler, '_request_with_wall_clock_deadline', counter): + failed = await pubnub.publish().channel(channel).message('x').future() + a.ok(failed.is_error(), 'publishing without a publish key fails') + a.eq(str(failed.status.error_data.exception), 'Publish key not configured', 'exact error text') + a.eq(counter.calls, 0, 'no request was sent') + + # It still reads: the same config with the real subscribe key receives a message another client published + pnconfig.origin = client_config('open').origin + pnconfig.subscribe_key = client_config('open').subscribe_key + seen = await alisten(pubnub, channel) + await aclients.asyncio('open', 'writer').publish().channel(channel).message('read-me').future() + + async def received(): + a.eq([m.message for m in seen.messages], ['read-me'], 'the read-only client received') + await aeventually(received) + + +async def test_initialize_access_manager(aclients): + """Snippet: initialize_access_manager.""" + # snippet.initialize_access_manager + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio + + pnconfig = PNConfiguration() + pnconfig.subscribe_key = "my_subkey" + pnconfig.publish_key = "my_pubkey" + pnconfig.secret_key = "my_secretkey" + pnconfig.user_id = "my_custom_user_id" + pnconfig.ssl = True + + pubnub = PubNubAsyncio(pnconfig) + # snippet.end + a.eq(pnconfig.secret_key, 'my_secretkey') + aclients._made.append(pubnub) + + counter = RequestCounter() + pnconfig.origin = UNREACHABLE + with mock.patch.object(AsyncHttpxRequestHandler, '_request_with_wall_clock_deadline', counter): + with mock.patch('warnings.warn'): + with_secret = await pubnub.grant().channels('x').read(True).future() + a.eq(counter.calls, 1, 'the grant call reaches the network layer once the secret key is configured') + a.ok(with_secret.is_error(), 'the stand-in refused the request') + keyless = aclients.asyncio('open', 'no_secret') + without = await keyless.grant().channels('x').read(True).future() + a.eq(str(without.status.error_data.exception), 'Secret key is not configured', 'exact error text') + a.eq(counter.calls, 1, 'without a secret key no request is built') + + +async def test_initialize_custom_event_loop(aclients): + """Snippet: initialize_custom_event_loop.""" + my_event_loop = asyncio.get_running_loop() + + # snippet.initialize_custom_event_loop + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio + + pnconfig = PNConfiguration() + pnconfig.subscribe_key = "my_subkey" + pnconfig.publish_key = "my_pubkey" + pnconfig.user_id = "my_custom_user_id" + + pubnub = PubNubAsyncio(pnconfig, custom_event_loop=my_event_loop) + # snippet.end + a.ok(pubnub.event_loop is my_event_loop, 'the client runs on the given loop') + await works(aclients, pubnub, pnconfig) + + +async def test_set_filter_expression(aclients): + """Snippets: set_filter_expression, get_filter_expression.""" + channel = 'my_channel' + + # snippet.set_filter_expression + from pubnub.pnconfiguration import PNConfiguration + + pnconfig = PNConfiguration() + pnconfig.filter_expression = "such == 'wow'" + # snippet.end + real_keys(pnconfig) + pnconfig.user_id = 'filtered' + # The default subscribe loop (EventEngineSubscriptionManager) ignores filter_expression (SDK bug, see the report), + # so this step uses the documented subscription_manager argument of the constructor to select the loop that sends + # the filter. + filtered = PubNubAsyncio(pnconfig, subscription_manager=AsyncioSubscriptionManager) + aclients._made.append(filtered) + seen = await alisten(filtered, channel) + publisher = aclients.asyncio('open', 'filter_publisher') + await publisher.publish().channel(channel).message('no-meta').future() + await publisher.publish().channel(channel).message('other').meta({'such': 'meh'}).future() + await publisher.publish().channel(channel).message('matching').meta({'such': 'wow'}).future() + + async def only_matching(): + a.eq([m.message for m in seen.messages], ['matching'], 'only the matching message arrived') + await aeventually(only_matching) + + # snippet.get_filter_expression + filter = pnconfig.filter_expression + # snippet.end + a.eq(filter, "such == 'wow'") + a.eq(client_config('open').filter_expression, None, 'the default is no filter') diff --git a/tests/live/asyncio/api_reference/test_file_sharing.py b/tests/live/asyncio/api_reference/test_file_sharing.py new file mode 100644 index 00000000..7779a166 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_file_sharing.py @@ -0,0 +1,223 @@ +"""Docs page: file sharing (asyncio). Source: docs/sdks/asyncio/api-reference/files.md. Same contract as sync.""" +import asyncio +import os +import tempfile + +from support import assertions as a +from support.wait import aeventually, asettled +from shared.file_sharing import ( + FIXTURE, FIXTURE_BYTES, channel_name_async as channel_name, fetch, listed_ids_async as listed_ids, + remove_async as remove, stored_file_messages_async as stored_file_messages, upload_async as upload, +) + + +async def test_send_file_builder(aclients, monkeypatch): + """Snippets: send_file_builder, send_file_options.""" + pubnub = aclients.asyncio('open', 'file_sender') + monkeypatch.chdir(FIXTURE.parent) # the samples open "sample.gif" from the working directory + sent = [] + try: + # snippet.send_file_builder + with open("sample.gif", "rb") as fd: + envelope = await pubnub.send_file() \ + .channel("test_channel") \ + .file_name("knights_of_ni.jpg") \ + .message({"test_message": "test"}) \ + .should_store(True) \ + .file_object(fd) \ + .future() + + if envelope.status.is_error(): + print("Error sending file") + else: + print(f"File sent successfully: {envelope.result.name}") + # snippet.end + sent.append(envelope.result) + a.ok(not envelope.status.is_error(), 'status is not an error') + a.eq(envelope.result.name, 'knights_of_ni.jpg') + a.ok(envelope.result.file_id, 'file id returned') + a.timetoken(envelope.result.timestamp) + + # snippet.send_file_options + with open("sample.gif", "rb") as fd: + envelope_2 = await pubnub.send_file() \ + .channel("test_channel") \ + .file_name("knights_of_ni.jpg") \ + .message({"test_message": "test"}) \ + .should_store(True) \ + .ttl(222) \ + .file_object(fd) \ + .future() + if envelope_2.is_error(): + print(f"Error: {envelope_2.status.error_data}") + # snippet.end + sent.append(envelope_2.result) + both = (envelope.result.file_id, envelope_2.result.file_id) + a.ok(both[0] != both[1], 'every upload gets its own id') + + async def two_stored(): + a.eq(len(await stored_file_messages(pubnub, *both)), 2, 'file events stored') + await aeventually(two_stored) + stored = {m.message['file']['id']: m for m in await stored_file_messages(pubnub, *both)} + a.eq(stored[both[0]].message['message'], {'test_message': 'test'}) + a.eq(stored[both[0]].message['file']['name'], 'knights_of_ni.jpg') + a.eq(str(stored[both[0]].timetoken), str(envelope.result.timestamp), 'the message carries the timestamp') + + async def listed(): + a.contains(await listed_ids(pubnub), both[0], 'listed after upload') + await aeventually(listed) + listing = (await pubnub.list_files().channel(channel_name()).future()).result.data + entry = [item for item in listing if item['id'] == both[0]][0] + a.eq(entry['size'], len(FIXTURE_BYTES), 'listed size is the fixture size') + finally: + await remove(pubnub, *sent) + + +async def test_list_files_builder(aclients): + """Snippet: list_files_builder.""" + pubnub = aclients.asyncio('open', 'file_lister') + first, second = await upload(pubnub), await upload(pubnub) + try: + async def both_listed(): + a.contains(await listed_ids(pubnub), second.file_id, 'second upload listed') + await asettled(both_listed) + + # snippet.list_files_builder + envelope = await pubnub.list_files().channel("test_channel").limit(1).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + next_page = await pubnub.list_files().channel("test_channel").limit(1).next(envelope.result.next).future() + if next_page.is_error(): + print(f"Error: {next_page.status.error_data}") + # snippet.end + a.eq(len(envelope.result.data), 1, 'first page has the limit') + a.eq(len(next_page.result.data), 1, 'second page has the limit') + a.eq({envelope.result.data[0]['id'], next_page.result.data[0]['id']}, {first.file_id, second.file_id}) + a.ok({'id', 'name', 'size', 'created'} <= set(envelope.result.data[0]), 'file entry keys') + everything = await pubnub.list_files().channel(channel_name()).future() + a.eq(everything.result.count, len(everything.result.data), 'count matches the page') + finally: + await remove(pubnub, first, second) + + +async def test_get_file_url_builder(aclients): + """Snippet: get_file_url_builder.""" + pubnub = aclients.asyncio('open', 'file_url_reader') + uploaded = await upload(pubnub) + try: + # snippet.get_file_url_builder + envelope = await pubnub.get_file_url(). \ + channel("test_channel"). \ + file_id(uploaded.file_id). \ + file_name(uploaded.name).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + url = envelope.result.file_url + a.ok(url.startswith('https://'), 'url scheme') + a.contains(url, uploaded.file_id) + status, body = await asyncio.get_running_loop().run_in_executor(None, fetch, url) + a.eq(status, 200, 'the url serves the file') + a.eq(body, FIXTURE_BYTES, 'the url serves the same bytes') + finally: + await remove(pubnub, uploaded) + + +async def test_download_file_builder(aclients, monkeypatch): + """Snippet: download_file_builder.""" + pubnub = aclients.asyncio('open', 'file_downloader') + uploaded = await upload(pubnub) + target = tempfile.mkdtemp(prefix='pubnub-live-') + saved_file = os.path.join(target, uploaded.name) + monkeypatch.chdir(target) # the sample saves the file in the working directory + try: + # snippet.download_file_builder + download_envelope = await pubnub.download_file(). \ + channel("test_channel"). \ + file_id(uploaded.file_id). \ + file_name(uploaded.name).future() + if download_envelope.is_error(): + print(f"Error: {download_envelope.status.error_data}") + else: + save_path = uploaded.name + with open(save_path, "wb") as fw: + fw.write(download_envelope.result.data) + # snippet.end + a.eq(download_envelope.result.data, FIXTURE_BYTES, 'downloaded bytes equal the upload') + a.eq(os.path.realpath(save_path), os.path.realpath(saved_file), 'saved in the working directory') + with open(saved_file, 'rb') as saved: + a.eq(saved.read(), FIXTURE_BYTES, 'saved bytes equal the upload') + finally: + await remove(pubnub, uploaded) + if os.path.exists(saved_file): + os.remove(saved_file) + os.rmdir(target) + + +async def test_delete_file_builder(aclients): + """Snippet: delete_file_builder.""" + pubnub = aclients.asyncio('open', 'file_deleter') + one, two = await upload(pubnub), await upload(pubnub) + remaining = [one, two] + try: + async def both_listed(): + a.contains(await listed_ids(pubnub), two.file_id, 'uploads listed') + await asettled(both_listed) + + # snippet.delete_file_builder + envelope = await pubnub.delete_file(). \ + channel("test_channel"). \ + file_id(one.file_id). \ + file_name(one.name).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + remaining.remove(one) + a.eq(envelope.result.status, 200, 'delete status') + + async def gone(): + a.not_contains(await listed_ids(pubnub), one.file_id, 'deleted file still listed') + await aeventually(gone) + a.contains(await listed_ids(pubnub), two.file_id, 'the other file is untouched') + missing = await pubnub.download_file().channel(channel_name()).file_id(one.file_id) \ + .file_name(one.name).future() + a.ok(missing.is_error(), 'a deleted file cannot be downloaded') + a.eq(missing.status.status_code, 404, 'the service answers not found') + finally: + await remove(pubnub, *remaining) + + +async def test_publish_file_message_builder(aclients): + """Snippet: publish_file_message_builder.""" + pubnub = aclients.asyncio('open', 'file_publisher') + uploaded = await upload(pubnub) + try: + async def uploaded_stored(): + a.eq(len(await stored_file_messages(pubnub, uploaded.file_id)), 1, 'upload stored a message') + await aeventually(uploaded_stored) + + # snippet.publish_file_message_builder + envelope = await pubnub.publish_file_message(). \ + channel("test_channel"). \ + meta({"test": "test"}). \ + message({"test_message": "test"}). \ + file_id(uploaded.file_id). \ + file_name(uploaded.name). \ + should_store(True). \ + ttl(22).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.timetoken(envelope.result.timestamp) + + async def message_stored(): + a.eq(len(await stored_file_messages(pubnub, uploaded.file_id)), 2, 'file message stored') + await aeventually(message_stored) + stored = await stored_file_messages(pubnub, uploaded.file_id) + event = [m for m in stored if str(m.timetoken) == str(envelope.result.timestamp)][0] + a.eq(event.message['file'], {'id': uploaded.file_id, 'name': uploaded.name}) + a.eq(event.message['message'], {'test_message': 'test'}) + a.eq(event.meta, {'test': 'test'}) + finally: + await remove(pubnub, uploaded) diff --git a/tests/live/asyncio/api_reference/test_message_actions.py b/tests/live/asyncio/api_reference/test_message_actions.py new file mode 100644 index 00000000..e53924d6 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_message_actions.py @@ -0,0 +1,178 @@ +"""Docs page: message actions (asyncio). Same steps as sync/message_actions.py with await. + +A message action needs a stored message, so every step waits until the published message is readable from history. +""" +from support import assertions as a +from support.listen import alisten +from support.wait import aeventually, asettled +from shared.message_actions import add_action_async as add_action, publish_stored_async as publish_stored, remove_action + + +async def test_add_message_action_builder(aclients): + """Snippets: add_message_action_builder, add_message_action_named.""" + pubnub = aclients.asyncio('open', 'reactor') + channel = 'chats.room1' + seen = await alisten(aclients.asyncio('open', 'watcher'), channel) + message_timetoken = (await publish_stored(pubnub, channel))[0] + + # snippet.add_message_action_builder + from pubnub.models.consumer.message_actions import PNMessageAction + msg_action = PNMessageAction() + msg_action.type = "reaction" + msg_action.value = "smiley_face" + msg_action.message_timetoken = message_timetoken + + envelope = await pubnub.add_message_action() \ + .channel("chats.room1") \ + .message_action(msg_action) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + print(f"Added action at timetoken: {envelope.result.action_timetoken}") + # snippet.end + + added = envelope.result + a.eq(envelope.status.is_error(), False) + a.timetoken(added.action_timetoken) + a.eq((added.type, added.value, added.uuid), ('reaction', 'smiley_face', pubnub.uuid)) + a.eq(int(added.message_timetoken), message_timetoken) + await aeventually(lambda: a.eq(len(seen.message_actions), 1, 'action events received')) + event = seen.message_actions[0] + a.eq((event.type, event.value, event.uuid), ('reaction', 'smiley_face', pubnub.uuid)) + a.eq(event.action_timetoken, added.action_timetoken) + a.eq(int(event.message_timetoken), message_timetoken) + a.eq(event.channel, channel) + + # snippet.add_message_action_named + from pubnub.models.consumer.message_actions import PNMessageAction + + msg_action = PNMessageAction() + msg_action.type = "reaction" + msg_action.value = "thumbs_up" + msg_action.message_timetoken = message_timetoken + + envelope = await pubnub.add_message_action( + channel="chats.room1", + message_action=msg_action + ).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + print(f"Added action at timetoken: {envelope.result.action_timetoken}") + # snippet.end + a.eq(envelope.result.value, 'thumbs_up') + + async def read_back(): + got = await pubnub.fetch_messages(channels=[channel], count=1, include_message_actions=True).future() + actions = got.result.channels[channel][0].actions + a.eq(sorted(actions['reaction']), ['smiley_face', 'thumbs_up'], 'fetch shows both actions') + a.eq(actions['reaction']['smiley_face'][0]['actionTimetoken'], added.action_timetoken) + a.eq(actions['reaction']['smiley_face'][0]['uuid'], pubnub.uuid) + + await aeventually(read_back, timeout=30, what='actions visible through fetch_messages') + await aeventually(lambda: a.eq(len(seen.message_actions), 2, 'second action event received')) + for action_timetoken in (added.action_timetoken, envelope.result.action_timetoken): + await remove_action(pubnub, channel, message_timetoken, action_timetoken) + + +async def test_get_message_actions_builder(aclients): + """Snippets: get_message_actions_builder, get_message_actions_named.""" + pubnub = aclients.asyncio('open', 'reader') + channel = 'chats.room1' + tokens = await publish_stored(pubnub, channel, 3) + first, second, third = [(await add_action(pubnub, channel, tt, 'smiley_face')).action_timetoken for tt in tokens] + a.ok(first < second < third, 'action timetokens grow') + + async def all_visible(): + got = (await pubnub.get_message_actions(channel=channel).future()).result.actions + mine = [x.action_timetoken for x in got if int(x.message_timetoken) in tokens] + a.eq(mine, [first, second, third], 'ascending by action timetoken') + + await asettled(all_visible, timeout=30, what='actions listed') + start, end = str(third), str(second) + + # snippet.get_message_actions_builder + envelope = await pubnub.get_message_actions() \ + .channel("chats.room1") \ + .start(start) \ + .end(end) \ + .limit("50") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + for action in envelope.result.actions: + print(f"Message Action type: {action.type}") + print(f"Message Action value: {action.value}") + print(f"Message Action timetoken: {action.message_timetoken}") + print(f"Message Action uuid: {action.uuid}") + print(f"Message Action timetoken: {action.action_timetoken}") + # snippet.end + + built = envelope.result.actions + a.eq(len(built) > 0 and built[-1].uuid, pubnub.uuid) + + # snippet.get_message_actions_named + envelope = await pubnub.get_message_actions(channel="chats.room1", start=start, end=end, limit="50").future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + named = envelope.result.actions + limited = (await pubnub.get_message_actions(channel=channel, limit="2").future()).result.actions + a.eq(len(limited), 2, 'limit caps the list') + for token, action_timetoken in zip(tokens, (first, second, third)): + await remove_action(pubnub, channel, token, action_timetoken) + # Last on purpose: the SDK sends no end boundary when a start boundary is set (get_message_actions.py:50). + a.eq([x.action_timetoken for x in built], [second], 'builder: start excluded, end included') + a.eq(int(built[0].message_timetoken), tokens[1]) + a.eq([x.action_timetoken for x in named], [second], 'named arguments: same range') + + +async def test_remove_message_action_builder(aclients): + """Snippets: remove_message_action_builder, remove_message_action_named.""" + pubnub = aclients.asyncio('open', 'remover') + channel = 'chats.room1' + seen = await alisten(aclients.asyncio('open', 'watcher'), channel) + message_timetoken = (await publish_stored(pubnub, channel))[0] + first = (await add_action(pubnub, channel, message_timetoken, 'smiley_face')).action_timetoken + second = (await add_action(pubnub, channel, message_timetoken, 'thumbs_up')).action_timetoken + await aeventually(lambda: a.eq(len(seen.message_actions), 2, 'added events received')) + + async def listed(expected): + got = (await pubnub.get_message_actions(channel=channel).future()).result.actions + a.eq([x.action_timetoken for x in got if int(x.message_timetoken) == message_timetoken], expected) + + await asettled(lambda: listed([first, second]), timeout=30, what='both actions listed') + action_timetoken = int(first) + + # snippet.remove_message_action_builder + envelope = await pubnub.remove_message_action() \ + .channel("chats.room1") \ + .action_timetoken(action_timetoken) \ + .message_timetoken(message_timetoken) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.status.is_error(), False) + a.eq(envelope.result, {}) + await aeventually(lambda: listed([second]), timeout=30, what='first action removed') + await aeventually(lambda: a.eq(len(seen.message_actions), 3, 'removed event received')) + a.eq(seen.message_actions[2].action_timetoken, first) + + action_timetoken = int(second) + # snippet.remove_message_action_named + envelope = await pubnub.remove_message_action(channel="chats.room1", + action_timetoken=action_timetoken, + message_timetoken=message_timetoken) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.result, {}) + await aeventually(lambda: listed([]), timeout=30, what='second action removed') + await aeventually(lambda: a.eq(len(seen.message_actions), 4, 'second removed event received')) + a.eq(seen.message_actions[3].action_timetoken, second) + got = await pubnub.fetch_messages(channels=[channel], count=1, include_message_actions=True).future() + a.eq(got.result.channels[channel][0].actions, {}, 'history shows no actions') diff --git a/tests/live/asyncio/api_reference/test_message_persistence.py b/tests/live/asyncio/api_reference/test_message_persistence.py new file mode 100644 index 00000000..7f47883d --- /dev/null +++ b/tests/live/asyncio/api_reference/test_message_persistence.py @@ -0,0 +1,290 @@ +"""Docs page: message persistence (asyncio). Same steps as sync/message_persistence.py with await. + +Each step seeds its own messages and reads them back through bounds made of the seeded timetokens, so leftovers on a +shared channel name from an earlier run of this page (for example the sync one) never change a result. +""" +import pytest + +from support import assertions as a +from support.wait import aeventually, asettled +from shared.message_persistence import ( + seed_async as seed, seed_parallel_async as seed_parallel, wait_stored_async as wait_stored, + window_async as window, +) + + +async def test_fetch_history_builder(aclients): + """Snippets: fetch_history_builder, fetch_history_named.""" + pubnub = aclients.asyncio('open', 'fetcher') + channel = 'my_channel' + seeded = await seed(pubnub, channel, 3, meta={'origin': 'docs'}, custom_message_type='text-message') + await wait_stored(pubnub, channel, [tt for _, tt in seeded]) + last_message, last_timetoken = seeded[-1] + + # snippet.fetch_history_builder + envelope = await pubnub.fetch_messages() \ + .channels(["my_channel"]) \ + .maximum_per_channel(1) \ + .include_message_actions(True) \ + .include_meta(True) \ + .include_message_type(True) \ + .include_uuid(True) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + for message in envelope.result.channels["my_channel"]: + print("Message: %s" % message.message) + print("Meta: %s" % message.meta) + print("Timetoken: %s" % message.timetoken) + + for action_type in message.actions: + print("Message Action type: " + action_type) + # snippet.end + + def check(items): + a.eq(len(items), 1, 'maximum_per_channel(1) returns one message') + a.eq(items[0].message, last_message) + a.eq(int(items[0].timetoken), last_timetoken) + a.eq(items[0].meta, {'origin': 'docs'}) + a.eq(items[0].uuid, pubnub.uuid) + a.ok(hasattr(items[0], 'message_type'), 'include_message_type adds message_type') + a.eq(items[0].actions, {}, 'no actions yet') + + check(envelope.result.channels[channel]) + + # snippet.fetch_history_named + envelope = await pubnub.fetch_messages(channels=["my_channel"], count=1, include_message_actions=True, + include_meta=True, include_message_type=True, include_uuid=True).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + for message in envelope.result.channels["my_channel"]: + print(f"Message: {message.message}") + print(f"Meta: {message.meta}") + print(f"Timetoken: {message.timetoken}") + # snippet.end + check(envelope.result.channels[channel]) + a.eq(sorted(envelope.result.channels), [channel]) + + +async def test_fetch_history_range(aclients): + """Snippet: fetch_history_range.""" + pubnub = aclients.asyncio('open', 'ranger') + channel = 'my_channel' + seeded = await seed(pubnub, channel, 5) + tokens = [tt for _, tt in seeded] + messages = [m for m, _ in seeded] + await wait_stored(pubnub, channel, tokens) + newer_timetoken, older_timetoken = tokens[3], tokens[1] + + # snippet.fetch_history_range + envelope = await pubnub.fetch_messages() \ + .channels(["my_channel"]) \ + .start(newer_timetoken) \ + .end(older_timetoken) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + + got = envelope.result.channels[channel] + a.eq([int(i.timetoken) for i in got], [tokens[1], tokens[2]], 'start excluded, end included, oldest first') + a.eq([i.message for i in got], messages[1:3]) + only_start = await pubnub.fetch_messages(channels=[channel], start=tokens[3], end=tokens[0]).future() + a.eq([int(i.timetoken) for i in only_start.result.channels[channel]], tokens[0:3], 'older than start') + only_end = (await pubnub.fetch_messages(channels=[channel], end=tokens[2]).future()).result.channels[channel] + a.eq([int(i.timetoken) for i in only_end][:3], tokens[2:5], 'end only: newer than or equal to end') + a.eq(int(only_end[-1].timetoken), tokens[4], 'end only: includes the newest message') + + +@pytest.mark.timeout(300) +async def test_fetch_history_multiple(aclients): + """Snippet: fetch_history_multiple.""" + pubnub = aclients.asyncio('open', 'capper') + channel = 'my_channel' + first = 'ch1' + second = 'ch2' + single = await seed_parallel(pubnub, channel, 101) + on_first = await seed_parallel(pubnub, first, 26) + on_second = await seed_parallel(pubnub, second, 26) + + async def single_stored(): + got = (await pubnub.fetch_messages(channels=[channel], count=150).future()).result.channels[channel] + a.eq([int(i.timetoken) for i in got], single[1:], 'newest 100 of 101') + + await asettled(single_stored, timeout=30, what='seeded messages stored') + + async def newest_stored(): + got = (await pubnub.fetch_messages(channels=[first, second], count=30).future()).result.channels + a.eq([int(i.timetoken) for i in got[first]], on_first[1:], 'newest 25 of ch1') + a.eq([int(i.timetoken) for i in got[second]], on_second[1:], 'newest 25 of ch2') + + await asettled(newest_stored, timeout=30, what='seeded messages on both channels stored') + + # snippet.fetch_history_multiple + envelope = await pubnub.fetch_messages() \ + .channels(["ch1", "ch2"]) \ + .maximum_per_channel(30) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + for channel_name, items in envelope.result.channels.items(): + print(channel_name, len(items)) + # snippet.end + + for name in (first, second): + a.eq(len(envelope.result.channels[name]), 25, 'several channels: at most 25 per channel') + one = (await pubnub.fetch_messages(channels=[channel], count=150).future()).result.channels[channel] + a.eq(len(one), 100, 'one channel: at most 100 messages') + a.eq([int(i.timetoken) for i in one], single[1:], 'the newest 100, oldest first') + + +async def test_message_counts_builder(aclients): + """Snippets: message_counts_builder, message_counts_named, message_counts_multiple_builder, + message_counts_multiple_named.""" + pubnub = aclients.asyncio('open', 'counter') + channel = 'my_channel' + other = 'my_channel_2' + seeded = await seed(pubnub, channel, 4) + tokens = [tt for _, tt in seeded] + on_other = [tt for _, tt in await seed(pubnub, other, 2)] + await wait_stored(pubnub, channel, tokens) + await wait_stored(pubnub, other, on_other) + timetoken = tokens[0] + other_timetoken = on_other[0] + + def counted(envelope, expected): + a.eq(envelope.result.channels, expected) + + async def counted_eventually(build, expected): + async def check(): + counted(await build(), expected) + + await aeventually(check, timeout=30, what='message counts') + + # The service counts messages newer than the timetoken, the message at the timetoken itself is not counted. + await counted_eventually( + lambda: pubnub.message_counts(channels=channel, channels_timetoken=[timetoken - 1]).future(), {channel: 4}) + await counted_eventually( + lambda: pubnub.message_counts(channels=channel, channels_timetoken=[timetoken]).future(), {channel: 3}) + + # snippet.message_counts_builder + envelope = await pubnub.message_counts() \ + .channel("my_channel") \ + .channel_timetokens([timetoken]) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + print(envelope.result.channels["my_channel"]) + # snippet.end + counted(envelope, {channel: 3}) + + # snippet.message_counts_named + envelope = await pubnub.message_counts(channels="my_channel", channels_timetoken=[tokens[2]]).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + counted(envelope, {channel: 1}) + await counted_eventually( + lambda: pubnub.message_counts(channels=channel, channels_timetoken=[tokens[3]]).future(), {channel: 0}) + + # snippet.message_counts_multiple_builder + envelope = await pubnub.message_counts() \ + .channel(["my_channel", "my_channel_2"]) \ + .channel_timetokens([timetoken, other_timetoken]) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + print(envelope.result.channels) + # snippet.end + counted(envelope, {channel: 3, other: 1}) + + # snippet.message_counts_multiple_named + envelope = await pubnub.message_counts(channels=["my_channel", "my_channel_2"], + channels_timetoken=[tokens[1], other_timetoken]).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + counted(envelope, {channel: 2, other: 1}) + + +async def test_delete_messages_builder(aclients): + """Snippets: delete_messages_builder, delete_messages_named.""" + pubnub = aclients.asyncio('open', 'deleter') + channel = 'my_channel' + seeded = await seed(pubnub, channel, 4) + tokens = [tt for _, tt in seeded] + await wait_stored(pubnub, channel, tokens) + newer_timetoken, older_timetoken = tokens[2], tokens[1] + + # snippet.delete_messages_builder + envelope = await pubnub.delete_messages() \ + .channel("my_channel") \ + .start(newer_timetoken) \ + .end(older_timetoken) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + detail = getattr(envelope.status.error_data, 'information', None) + a.eq(envelope.status.is_error(), False, 'delete failed: %s' % detail) + + async def left(expected): + got = [int(i.timetoken) for i in await window(pubnub, channel, tokens[3], tokens[0])] + a.eq(got, expected) + + await aeventually(lambda: left([tokens[0], tokens[2], tokens[3]]), timeout=30, + what='only the message at end is deleted') + + # snippet.delete_messages_named + envelope = await pubnub.delete_messages(channel="my_channel", start=tokens[3], end=tokens[2]).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + detail = getattr(envelope.status.error_data, 'information', None) + a.eq(envelope.status.is_error(), False, 'delete failed: %s' % detail) + await aeventually(lambda: left([tokens[0], tokens[3]]), timeout=30, what='the second message is deleted') + + +async def test_delete_message_single_builder(aclients): + """Snippets: delete_message_single_builder, delete_message_single_named.""" + pubnub = aclients.asyncio('open', 'single_deleter') + channel = 'my_channel' + seeded = await seed(pubnub, channel, 3) + tokens = [tt for _, tt in seeded] + await wait_stored(pubnub, channel, tokens) + publish_timetoken = tokens[1] + + # snippet.delete_message_single_builder + envelope = await pubnub.delete_messages() \ + .channel("my_channel") \ + .start(publish_timetoken - 1) \ + .end(publish_timetoken) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + detail = getattr(envelope.status.error_data, 'information', None) + a.eq(envelope.status.is_error(), False, 'delete failed: %s' % detail) + + async def left(expected): + got = [int(i.timetoken) for i in await window(pubnub, channel, tokens[2], tokens[0])] + a.eq(got, expected) + + await aeventually(lambda: left([tokens[0], tokens[2]]), timeout=30, + what='exactly the published message is deleted') + + publish_timetoken = tokens[2] + # snippet.delete_message_single_named + envelope = await pubnub.delete_messages(channel="my_channel", start=publish_timetoken - 1, + end=publish_timetoken).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + detail = getattr(envelope.status.error_data, 'information', None) + a.eq(envelope.status.is_error(), False, 'delete failed: %s' % detail) + await aeventually(lambda: left([tokens[0]]), timeout=30, what='the last message is deleted') diff --git a/tests/live/asyncio/api_reference/test_message_persistence_legacy.py b/tests/live/asyncio/api_reference/test_message_persistence_legacy.py new file mode 100644 index 00000000..cd5455cb --- /dev/null +++ b/tests/live/asyncio/api_reference/test_message_persistence_legacy.py @@ -0,0 +1,143 @@ +"""Docs page: message-persistence-legacy (asyncio). The samples of the legacy page.""" +import contextlib +import io + +import pytest + +from support import assertions as a +from support.wait import asettled +from shared.message_persistence import check_paging, seed_async as seed, seed_parallel_async as seed_parallel + + +async def test_history_basic(aclients): + """Snippets: history_basic, history_reverse, history_start_reverse, history_end, history_include_timetoken.""" + pubnub = aclients.asyncio('open', 'historian') + channel = 'history_channel_2' + seeded = await seed(pubnub, channel, 5) + tokens = [tt for _, tt in seeded] + messages = [m for m, _ in seeded] + + async def stored(): + got = await pubnub.history().channel(channel).count(100).future() + a.eq(len(got.result.messages), 5) + + await asettled(stored, timeout=30, what='seeded messages stored') + + # snippet.history_basic + envelope = await pubnub.history() \ + .channel("history_channel_2") \ + .count(100) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq([m.entry for m in envelope.result.messages], messages, 'oldest first, newest last') + a.eq(envelope.result.start_timetoken, tokens[0]) + a.eq(envelope.result.end_timetoken, tokens[4]) + + # snippet.history_reverse + envelope = await pubnub.history() \ + .channel("history_channel_2") \ + .count(3) \ + .reverse(True) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq([m.entry for m in envelope.result.messages], messages[0:3], 'the three oldest') + + # snippet.history_start_reverse + envelope = await pubnub.history() \ + .channel("history_channel_2") \ + .start(tokens[1]) \ + .reverse(True) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq([m.entry for m in envelope.result.messages], messages[2:], 'newer than start, start excluded') + + # snippet.history_end + envelope = await pubnub.history() \ + .channel("history_channel_2") \ + .count(100) \ + .end(tokens[2]) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq([m.entry for m in envelope.result.messages], messages[2:], 'end included, newest last') + # The docs sample adds start(-1) and reverse(True). The service refuses start(-1) and with reverse(True) the end + # timetoken becomes the newer boundary, so the result is the other half of the timeline. + refused = await pubnub.history().channel(channel).count(100).start(-1).end(tokens[2]).future() + a.eq((refused.status.is_error(), refused.status.status_code), (True, 400), 'start(-1) is refused with HTTP 400') + flipped = await pubnub.history().channel(channel).count(100).end(tokens[2]).reverse(True).future() + a.eq([m.entry for m in flipped.result.messages], messages[:3], 'reverse with end returns the older half') + + # snippet.history_include_timetoken + envelope = await pubnub.history() \ + .channel("history_channel_2") \ + .count(100) \ + .include_timetoken(True) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq([m.timetoken for m in envelope.result.messages], tokens) + a.eq([m.entry for m in envelope.result.messages], messages) + + +@pytest.mark.timeout(300) +async def test_history_paging(aclients): + """Snippet: history_paging.""" + pubnub = aclients.asyncio('open', 'pager') + channel = 'history_paging_channel_2' + tokens = await seed_parallel(pubnub, channel, 101) + + async def stored(): + got = await pubnub.history().channel(channel).count(100).future() + a.eq(len(got.result.messages), 100) + + await asettled(stored, timeout=30, what='seeded messages stored') + start_timetoken = tokens[-1] + 1 + + # snippet.history_paging + async def get_all_messages(start_tt): + envelope = await pubnub.history() \ + .channel("history_paging_channel_2") \ + .count(100) \ + .start(start_tt) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + return + msgs = envelope.result.messages + start = envelope.result.start_timetoken + end = envelope.result.end_timetoken + count = len(msgs) + + if count > 0: + print("%d" % count) + print("start %d" % start) + print("end %d" % end) + + if count == 100: + await get_all_messages(start) + # snippet.end + + output = io.StringIO() + with contextlib.redirect_stdout(output): + await get_all_messages(start_timetoken) + lines = output.getvalue().split('\n') + # The pages as the service holds them, read without the sample (a repeated publish is stored twice). + pages, cursor = [], start_timetoken + while True: + page = await pubnub.history().channel(channel).count(100).include_timetoken(True).start(cursor).future() + listed = [int(m.timetoken) for m in page.result.messages] + if not listed: + break + pages.append((len(listed), int(page.result.start_timetoken), int(page.result.end_timetoken), listed)) + if len(listed) < 100: + break + cursor = int(page.result.start_timetoken) + check_paging(lines, pages, tokens) diff --git a/tests/live/asyncio/api_reference/test_misc.py b/tests/live/asyncio/api_reference/test_misc.py new file mode 100644 index 00000000..81e545a4 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_misc.py @@ -0,0 +1,55 @@ +"""Docs page: miscellaneous utility methods (asyncio). Source: docs/sdks/asyncio/api-reference/misc.md.""" +import time + +from support import assertions as a +from support import cleanup as live_cleanup +from support.listen import alisten +from support.wait import aeventually + + +async def test_time_get(aclients): + """Snippet: time_get.""" + pubnub = aclients.asyncio('open', 'timekeeper') + + # snippet.time_get + envelope = await pubnub.time().future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + print(f"Current time: {envelope.result}") + # snippet.end + a.timetoken(str(envelope.result)) + a.eq(int(envelope.result), envelope.result.value_as_int) + a.ok(abs(int(envelope.result) / 10000000 - time.time()) < 120, 'server time is within two minutes of this host') + a.ok(abs(pubnub.timestamp() - int(time.time())) <= 1, 'timestamp() is int(time.time())') + a.eq(envelope.result.date_time().year, time.gmtime().tm_year) + + +async def test_get_subscribed_channels(aclients): + """Snippets: get_subscribed_channels, get_subscribed_channel_groups.""" + pubnub = aclients.asyncio('open', 'subscriber') + admin = aclients.asyncio('open', 'group_admin') + channel_a, channel_b = 'ch1', 'ch2' + group = 'cg1' + live_cleanup.record('channel_group', group) + try: + await admin.add_channel_to_channel_group().channels([channel_b]).channel_group(group).future() + await alisten(pubnub, channel_a, groups=[group]) + + # snippet.get_subscribed_channels + channels = pubnub.get_subscribed_channels() + # snippet.end + a.eq(channels, [channel_a]) + + # snippet.get_subscribed_channel_groups + channel_groups = pubnub.get_subscribed_channel_groups() + # snippet.end + a.eq(channel_groups, [group]) + pubnub.unsubscribe().channels(channel_a).channel_groups(group).execute() + + async def left(): + a.eq(pubnub.get_subscribed_channels(), [], 'channels after unsubscribe') + await aeventually(left) + a.eq(pubnub.get_subscribed_channel_groups(), [], 'groups after unsubscribe') + finally: + await admin.remove_channel_group().channel_group(group).future() diff --git a/tests/live/asyncio/api_reference/test_mobile_push.py b/tests/live/asyncio/api_reference/test_mobile_push.py new file mode 100644 index 00000000..55c13170 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_mobile_push.py @@ -0,0 +1,187 @@ +"""Docs page: mobile push (asyncio). Source: docs/sdks/asyncio/api-reference/mobile-push.md. + +Only the registration side is testable. A push is delivered by FCM or APNs to a real device, so delivery is not tested. +The device tokens are made up and fixed (support/resources.py PUSH_DEVICES), and every gateway is cleaned in a finally +block and by the janitor. +""" +from support import assertions as a +from shared.mobile_push import ( + APNS2_DEVICE, CHANNELS, clear_async as clear, expect_async as expect, seed_async as seed, suffixed, +) + + +async def test_add_channels_to_push_builder(aclients): + """Snippets: add_channels_to_push_builder, add_channels_to_push_kwargs.""" + pubnub = aclients.asyncio('open', 'push_registrar') + try: + a.ok(len(APNS2_DEVICE) == 64 and set(APNS2_DEVICE) <= set('0123456789abcdef'), 'apns2 token is 64 hex chars') + + # snippet.add_channels_to_push_builder + from pubnub.enums import PNPushEnvironment, PNPushType + + # for FCM + envelope = await pubnub.add_channels_to_push() \ + .push_type(PNPushType.FCM) \ + .channels(["ch1", "ch2", "ch3"]) \ + .device_id("deviceId") \ + .future() + + # for APNS2 + envelope = await pubnub.add_channels_to_push() \ + .push_type(PNPushType.APNS2) \ + .channels(["ch1", "ch2", "ch3"]) \ + .device_id("5646e7e88187c402636cf1a838175a1c3f5ccdff69d071e68630a73ab1a4955a") \ + .topic("myapptopic") \ + .environment(PNPushEnvironment.DEVELOPMENT) \ + .future() + + if envelope.status.is_error(): + print("Error adding device to channels for push notifications") + else: + print("Device added to channels successfully") + # snippet.end + a.ok(not envelope.status.is_error(), 'status is not an error') + await expect(pubnub, suffixed(CHANNELS), suffixed(CHANNELS), 'after add (builder)') + await clear(pubnub) + await expect(pubnub, [], [], 'after clearing') + + # snippet.add_channels_to_push_kwargs + from pubnub.enums import PNPushEnvironment, PNPushType + + kwargs = { + "push_type": PNPushType.FCM, + "channels": ["ch1", "ch2", "ch3"], + "device_id": "deviceId", + } + envelope = await pubnub.add_channels_to_push(**kwargs).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + + kwargs = { + "push_type": PNPushType.APNS2, + "channels": ["ch1", "ch2", "ch3"], + "device_id": "5646e7e88187c402636cf1a838175a1c3f5ccdff69d071e68630a73ab1a4955a", + "topic": "myapptopic", + "environment": PNPushEnvironment.DEVELOPMENT, + } + envelope = await pubnub.add_channels_to_push(**kwargs).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.ok(not envelope.status.is_error(), 'status is not an error') + await expect(pubnub, suffixed(CHANNELS), suffixed(CHANNELS), 'after add (keyword arguments)') + finally: + await clear(pubnub) + + +async def test_list_push_channels_builder(aclients): + """Snippet: list_push_channels_builder.""" + pubnub = aclients.asyncio('open', 'push_lister') + try: + await seed(pubnub, CHANNELS) + await expect(pubnub, suffixed(CHANNELS), suffixed(CHANNELS), 'after seeding') + + # snippet.list_push_channels_builder + from pubnub.enums import PNPushEnvironment, PNPushType + + # for FCM + envelope = await pubnub.list_push_channels() \ + .push_type(PNPushType.FCM) \ + .device_id("deviceId") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + fcm_channels = envelope.result.channels + + # for APNS2 + envelope = await pubnub.list_push_channels() \ + .push_type(PNPushType.APNS2) \ + .device_id("5646e7e88187c402636cf1a838175a1c3f5ccdff69d071e68630a73ab1a4955a") \ + .topic("myapptopic") \ + .environment(PNPushEnvironment.DEVELOPMENT) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + apns2_channels = envelope.result.channels + # snippet.end + a.eq(sorted(fcm_channels), suffixed(CHANNELS), 'fcm channels listed') + a.eq(sorted(apns2_channels), suffixed(CHANNELS), 'apns2 channels listed') + a.ok(not envelope.status.is_error(), 'status is not an error') + other = await pubnub.list_push_channels().push_type(PNPushType.FCM) \ + .device_id('unknown').future() + a.eq(other.result.channels, [], 'unknown device') + finally: + await clear(pubnub) + + +async def test_remove_channels_from_push_builder(aclients): + """Snippet: remove_channels_from_push_builder.""" + pubnub = aclients.asyncio('open', 'push_remover') + keep = 'keep_me' + try: + await seed(pubnub, CHANNELS + [keep]) + await expect(pubnub, suffixed(CHANNELS + [keep]), suffixed(CHANNELS + [keep]), 'after seeding') + + # snippet.remove_channels_from_push_builder + from pubnub.enums import PNPushEnvironment, PNPushType + + # for FCM + envelope = await pubnub.remove_channels_from_push() \ + .push_type(PNPushType.FCM) \ + .channels(["ch1", "ch2", "ch3"]) \ + .device_id("deviceId") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + + # for APNS2 + envelope = await pubnub.remove_channels_from_push() \ + .push_type(PNPushType.APNS2) \ + .channels(["ch1", "ch2", "ch3"]) \ + .device_id("5646e7e88187c402636cf1a838175a1c3f5ccdff69d071e68630a73ab1a4955a") \ + .topic("myapptopic") \ + .environment(PNPushEnvironment.DEVELOPMENT) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.ok(not envelope.status.is_error(), 'status is not an error') + await expect(pubnub, suffixed([keep]), suffixed([keep]), 'after remove, only the other channel is left') + finally: + await clear(pubnub) + + +async def test_remove_device_from_push_builder(aclients): + """Snippet: remove_device_from_push_builder.""" + pubnub = aclients.asyncio('open', 'push_device_remover') + try: + await seed(pubnub, CHANNELS) + await expect(pubnub, suffixed(CHANNELS), suffixed(CHANNELS), 'after seeding') + + # snippet.remove_device_from_push_builder + from pubnub.enums import PNPushEnvironment, PNPushType + + # for FCM + envelope = await pubnub.remove_device_from_push() \ + .push_type(PNPushType.FCM) \ + .device_id("deviceId") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + + # for APNS2 + envelope = await pubnub.remove_device_from_push() \ + .push_type(PNPushType.APNS2) \ + .device_id("5646e7e88187c402636cf1a838175a1c3f5ccdff69d071e68630a73ab1a4955a") \ + .topic("myapptopic") \ + .environment(PNPushEnvironment.DEVELOPMENT) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.ok(not envelope.status.is_error(), 'status is not an error') + await expect(pubnub, [], [], 'after remove all') + finally: + await clear(pubnub) diff --git a/tests/live/asyncio/api_reference/test_objects.py b/tests/live/asyncio/api_reference/test_objects.py new file mode 100644 index 00000000..df8c0141 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_objects.py @@ -0,0 +1,1268 @@ +"""Docs page: App Context (asyncio). User and channel metadata. + +Also channel memberships, channel members and the PNChannelMembership and PNUUID classes, because they are on the +same docs page. Same steps as sync/api_reference/test_objects.py with await. The helpers are in shared/objects.py. Every +object a test creates is removed in a finally block, and the janitor cleans the names listed in NAMES. The asyncio +client does not raise on an HTTP error, future() resolves with a PubNubAsyncioException, so the reads outside the +snippets go through attempt() and checked(). +""" +from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership +from pubnub.models.consumer.objects_v2.page import Next, Previous +from pubnub.models.consumer.objects_v2.common import MemberIncludes, MembershipIncludes +from pubnub.models.consumer.objects_v2.sort import PNSortKey, PNSortKeyValue +import pytest + +from support import assertions as a +from support.wait import asettled +from shared.objects import ( + CUSTOM_1, CUSTOM_2, UUID_FIELDS, attempt_async as attempt, by_channel, by_member, channel_ids, check_members, + check_memberships, checked, cleanup_async as cleanup, expect_error_async, first_event_async as first_event, + fresh_async as fresh, gone_async as gone, ids, member_ids, record, seed_channels_async as seed_channels, + seed_members_async as seed_members, seed_memberships_async as seed_memberships, + seed_one_member_async as seed_one_member, seed_one_membership_async as seed_one_membership, + seed_users_async as seed_users, settled_read_async as settled_read, watch_async as watch, +) + +# Every read after a write waits for consecutive agreeing reads (settled), and a test that asserts exact lists first +# removes the leftovers of both sides (fresh). Both cost time, so the default timeout of pytest.ini is too short. +pytestmark = pytest.mark.timeout(240) + + +async def memberships_of(pubnub, uid, **kwargs): + return (await attempt(lambda: pubnub.get_memberships(uuid=uid, **kwargs).future())).result.data + + +async def members_of(pubnub, channel, **kwargs): + return (await attempt(lambda: pubnub.get_channel_members(channel=channel, **kwargs).future())).result.data + + +async def uuid_data(pubnub, uid, **kwargs): + return (await attempt(lambda: pubnub.get_uuid_metadata(uuid=uid, **kwargs).future())).result.data + + +async def channel_data(pubnub, channel, **kwargs): + return (await attempt(lambda: pubnub.get_channel_metadata(channel=channel, **kwargs).future())).result.data + + +async def channels_of(pubnub, uid, **kwargs): + return channel_ids(await memberships_of(pubnub, uid, **kwargs)) + + +async def users_of(pubnub, channel, **kwargs): + return member_ids(await members_of(pubnub, channel, **kwargs)) + + +async def sorted_of(values): + return sorted(await values) + + +async def memberships_visible(pubnub, uid, plain, with_custom): + """Precondition: the seeded memberships with all details, on consecutive reads. A module-level helper, because + the samples import MembershipIncludes themselves, which makes the name local to the whole test function.""" + await settled_read(lambda: pubnub.get_memberships(uuid=uid, include=MembershipIncludes( + custom=True, channel=True, channel_custom=True)).future(), + lambda e: check_memberships(e.result.data, plain, with_custom), 'seeded memberships visible') + + +async def members_visible(pubnub, channel, plain, with_custom): + """Precondition: the seeded members with all details, on consecutive reads (see memberships_visible).""" + await settled_read(lambda: pubnub.get_channel_members(channel=channel, include=MemberIncludes( + custom=True, user=True, user_custom=True)).future(), + lambda e: check_members(e.result.data, plain, with_custom), 'seeded members visible') + + +async def settled_eq(read, want, what): + """read() (a coroutine function) equals want on consecutive reads (a write is visible on every replica).""" + async def once(): + a.eq(await read(), want, what) + await asettled(once, timeout=30, what=what) + + +async def test_get_all_uuid_metadata_builder(aclients): + """Snippets: get_all_uuid_metadata_builder, get_all_uuid_metadata_named.""" + pubnub = aclients.asyncio('open', 'lister') + kind = 'doc_type' + users = [('doc_user_' + x) for x in 'abc'] + record(uuids=users) + try: + for rank, uid in enumerate(users): + checked(await pubnub.set_uuid_metadata(uuid=uid, name=kind, type='doc', custom={'rank': rank}).future()) + + async def listed(page=None, **kwargs): + # the named arguments of get_all_uuid_metadata have no page, only the builder does + builder = pubnub.get_all_uuid_metadata(filter="name == '%s'" % kind, **kwargs) + return (await attempt(lambda: (builder.page(page) if page else builder).future())).result + + async def listed_ids(): + return ids((await listed()).data) + + await settled_eq(listed_ids, sorted(users), 'seeded users listed') + + # snippet.get_all_uuid_metadata_builder + from pubnub.models.consumer.objects_v2.sort import PNSortKey, PNSortKeyValue + result = await pubnub.get_all_uuid_metadata(include_custom=True, include_total_count=True) \ + .limit(10) \ + .filter("name == 'doc_type'") \ + .sort(PNSortKey.asc(PNSortKeyValue.ID), PNSortKey.desc(PNSortKeyValue.UPDATED)) \ + .page(None) \ + .future() + + for uuid_data in result.result.data: + print(f"UUID: {uuid_data['id']}") + print(f"Name: {uuid_data['name']}") + print(f"Custom: {uuid_data['custom']}") + # snippet.end + + built = result.result + a.eq(ids(built.data), users, 'ascending by id') + a.eq(built.total_count, 3, 'total count') + a.eq([u['custom'] for u in built.data], [{'rank': 0}, {'rank': 1}, {'rank': 2}]) + a.eq([u['name'] for u in built.data], [kind] * 3) + + # snippet.get_all_uuid_metadata_named + from pubnub.models.consumer.objects_v2.sort import PNSortKey, PNSortKeyValue + + metadata = await pubnub.get_all_uuid_metadata( + limit=10, + include_custom=True, + filter="name == 'doc_type'", + include_total_count=True, + sort_keys=[PNSortKey.asc(PNSortKeyValue.ID), PNSortKey.desc(PNSortKeyValue.UPDATED)] + ).future() + + for uuid_data in metadata.result.data: + print(f"UUID: {uuid_data['id']}") + print(f"Name: {uuid_data['name']}") + print(f"Custom: {uuid_data['custom']}") + # snippet.end + + a.eq(ids(metadata.result.data), users, 'named arguments: same list') + a.eq(metadata.result.total_count, 3) + a.eq([u['custom'] for u in metadata.result.data], [{'rank': 0}, {'rank': 1}, {'rank': 2}]) + + # Defaults: custom and the total count are omitted, status and type are returned. + plain = await listed() + a.not_contains(plain.data[0], 'custom', 'custom only when included') + a.eq(plain.data[0]['type'], 'doc') + a.contains(plain.data[0], 'status') + a.eq(plain.total_count, None, 'total count only when requested') + a.not_contains((await listed(include_type=False)).data[0], 'type', 'type can be left out') + a.not_contains((await listed(include_status=False)).data[0], 'status', 'status can be left out') + a.eq(ids((await listed(sort_keys=[PNSortKey.desc(PNSortKeyValue.ID)])).data), list(reversed(users)), + 'descending') + only = checked(await pubnub.get_all_uuid_metadata( + filter="name == '%s' && id == '%s'" % (kind, users[1])).future()) + a.eq(ids(only.result.data), [users[1]], 'filter on name and id') + + # Paging with next and prev + ordered = [PNSortKey.asc(PNSortKeyValue.ID)] + first = await listed(limit=2, sort_keys=ordered) + a.eq(ids(first.data), users[:2]) + a.ok(isinstance(first.next, Next), 'next page token') + a.eq(first.prev, None) + second = await listed(limit=2, sort_keys=ordered, page=first.next) + a.eq(ids(second.data), users[2:]) + a.ok(isinstance(second.prev, Previous), 'prev page token') + back = await listed(limit=2, sort_keys=ordered, page=second.prev) + a.eq(ids(back.data), users[:2], 'prev returns the first page') + finally: + await cleanup(pubnub, users) + + +async def test_get_uuid_metadata_builder(aclients): + """Snippets: get_uuid_metadata_builder, get_uuid_metadata_named.""" + pubnub = aclients.asyncio('open', 'profile') + me = pubnub.uuid + other = 'doc_other' + record(uuids=[me, other]) + try: + checked(await pubnub.set_uuid_metadata(uuid=me, name='Doc profile', status='Active', type='doc', + custom={'team': 'docs'}).future()) + checked(await pubnub.set_uuid_metadata(uuid=other, name='Doc other', custom={'team': 'other'}).future()) + + async def my_custom(): + return (await uuid_data(pubnub, me, include_custom=True))['custom'] + + async def other_custom(): + return (await uuid_data(pubnub, other, include_custom=True))['custom'] + + await settled_eq(my_custom, {'team': 'docs'}, 'profile visible') + await settled_eq(other_custom, {'team': 'other'}, 'other profile visible') + + # snippet.get_uuid_metadata_builder + envelope = await pubnub.get_uuid_metadata(include_custom=True).future() + # snippet.end + + data = envelope.result.data + a.eq(data['id'], me, 'defaults to the configured user id') + a.eq((data['name'], data['status'], data['type']), ('Doc profile', 'Active', 'doc')) + a.eq(data['custom'], {'team': 'docs'}) + a.eq(envelope.result.status, 200) + + # snippet.get_uuid_metadata_named + metadata = await pubnub.get_uuid_metadata(include_custom=True).future() + # snippet.end + + a.eq(metadata.result.data, data, 'named arguments: same object') + + plain = checked(await pubnub.get_uuid_metadata().future()).result.data + a.not_contains(plain, 'custom', 'custom only when included') + a.not_contains(checked(await pubnub.get_uuid_metadata(include_type=False).future()).result.data, 'type') + a.not_contains(checked(await pubnub.get_uuid_metadata(include_status=False).future()).result.data, 'status') + explicit = checked(await pubnub.get_uuid_metadata(uuid=other, include_custom=True).future()).result.data + a.eq((explicit['id'], explicit['custom']), (other, {'team': 'other'}), 'explicit uuid') + missing = 'doc_missing' + e = await expect_error_async(lambda: pubnub.get_uuid_metadata(uuid=missing).future(), '404') + a.contains(str(e), 'not found') + finally: + await cleanup(pubnub, [me, other]) + + +@pytest.mark.timeout(300) +async def test_set_uuid_metadata_builder(aclients): + """Snippets: set_uuid_metadata_builder, set_uuid_metadata_named.""" + pubnub = aclients.asyncio('open', 'setter') + first = 'some_uuid' + second = 'some_uuid_named' + record(uuids=[first, second]) + try: + seen = await watch(aclients, first) + + # snippet.set_uuid_metadata_builder + envelope = await pubnub.set_uuid_metadata(include_custom=True) \ + .uuid("some_uuid") \ + .set_name("Some Name") \ + .set_status("Active") \ + .set_type("User") \ + .email("test@example.com") \ + .profile_url("http://example.com") \ + .external_id("1234567890") \ + .custom({"key1": "val1", "key2": "val2"}) \ + .future() + # snippet.end + + data = envelope.result.data + a.eq({k: data[k] for k in UUID_FIELDS}, UUID_FIELDS) + a.eq((data['id'], data['custom']), (first, {'key1': 'val1', 'key2': 'val2'})) + a.ok(data['eTag'] and data['updated'], 'eTag and updated are returned') + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['id'], payload['name']), ('uuid', 'set', first, 'Some Name')) + a.eq(payload['custom'], {'key1': 'val1', 'key2': 'val2'}) + a.eq(payload['eTag'], data['eTag']) + await settled_eq(lambda: uuid_data(pubnub, first, include_custom=True), data, + 'read back equals the set response') + + seen = await watch(aclients, second) + + # snippet.set_uuid_metadata_named + envelope = await pubnub.set_uuid_metadata(uuid="some_uuid_named", + name="Some Name", + status="Active", type="User", + email="test@example.com", + profile_url="http://example.com", + external_id="1234567890", + custom={"key1": "val1", "key2": "val2"}, + include_custom=True) \ + .future() + # snippet.end + + named = envelope.result.data + a.eq({k: named[k] for k in UUID_FIELDS}, UUID_FIELDS) + a.eq((named['id'], named['custom']), (second, {'key1': 'val1', 'key2': 'val2'})) + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['id']), ('uuid', 'set', second)) + + # Custom is replaced as a whole, never merged + replaced = checked(await pubnub.set_uuid_metadata(uuid=first, custom={'only': 'this'}, + include_custom=True).future()).result.data + a.eq(replaced['custom'], {'only': 'this'}) + + async def first_custom(): + return (await uuid_data(pubnub, first, include_custom=True))['custom'] + + await settled_eq(first_custom, {'only': 'this'}, 'custom is overwritten') + + # Defaults of the include flags: status and type come back unless they are switched off + light = pubnub.set_uuid_metadata(uuid=first, name='Some Name', include_status=False, include_type=False) + light_data = checked(await light.future()).result.data + a.not_contains(light_data, 'status') + a.not_contains(light_data, 'type') + a.not_contains(light_data, 'custom', 'custom only when included') + + # Setting the same data again triggers no event. The first event the watcher sees is the later change. + fields = dict(name='Some Name', status='Active', type='User', custom={'only': 'this'}) + checked(await pubnub.set_uuid_metadata(uuid=first, **fields).future()) + same = await watch(aclients, first) + checked(await pubnub.set_uuid_metadata(uuid=first, **fields).future()) + fields['name'] = 'Renamed' + checked(await pubnub.set_uuid_metadata(uuid=first, **fields).future()) + kind, event, payload = await first_event(same) + a.eq((event, payload['name']), ('set', 'Renamed'), 'unchanged data raised no event') + finally: + await cleanup(pubnub, [first, second]) + + +async def test_remove_uuid_metadata_builder(aclients): + """Snippets: remove_uuid_metadata_builder, remove_uuid_metadata_named.""" + pubnub = aclients.asyncio('open', 'remover') + first = 'some_uuid' + second = 'some_uuid_named' + record(uuids=[first, second]) + try: + for uid in (first, second): + checked(await pubnub.set_uuid_metadata(uuid=uid, name='To remove', custom={'k': 'v'}).future()) + for uid in (first, second): + async def custom_of(): + return (await uuid_data(pubnub, uid, include_custom=True))['custom'] + + await settled_eq(custom_of, {'k': 'v'}, f'{uid} visible') + seen = await watch(aclients, first) + + # snippet.remove_uuid_metadata_builder + envelope = await pubnub.remove_uuid_metadata() \ + .uuid("some_uuid").future() + # snippet.end + + a.eq(envelope.result.status, 200) + a.eq(envelope.result.data, None, 'nothing is returned') + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['id']), ('uuid', 'delete', first)) + await gone(lambda: pubnub.get_uuid_metadata(uuid=first).future()) + + async def second_id(): + return (await uuid_data(pubnub, second))['id'] + + await settled_eq(second_id, second, 'other users stay') + + # snippet.remove_uuid_metadata_named + envelope = await pubnub.remove_uuid_metadata(uuid="some_uuid_named").future() + # snippet.end + + a.eq(envelope.result.status, 200) + await gone(lambda: pubnub.get_uuid_metadata(uuid=second).future()) + + async def listed_second(): + return (await attempt(lambda: pubnub.get_all_uuid_metadata( + filter="id == '%s'" % second).future())).result.data + + await settled_eq(listed_second, [], 'the list no longer has the user') + finally: + await cleanup(pubnub, [first, second]) + + +async def test_get_all_channel_metadata_builder(aclients): + """Snippets: get_all_channel_metadata_builder, get_all_channel_metadata_named.""" + pubnub = aclients.asyncio('open', 'lister') + kind = 'doc_type' + channels = [('doc_channel_' + x) for x in 'abc'] + record(channels=channels) + try: + for rank, channel in enumerate(channels): + checked(await pubnub.set_channel_metadata(channel=channel, name=kind, type='doc', + description='Channel %d' % rank, + custom={'rank': rank}).future()) + + async def listed(**kwargs): + call = pubnub.get_all_channel_metadata(filter="name == '%s'" % kind, **kwargs) + return (await attempt(lambda: call.future())).result + + async def listed_ids(): + return ids((await listed()).data) + + await settled_eq(listed_ids, sorted(channels), 'seeded channels listed') + + # snippet.get_all_channel_metadata_builder + from pubnub.models.consumer.objects_v2.sort import PNSortKey, PNSortKeyValue + envelope = await pubnub.get_all_channel_metadata(include_custom=True, include_total_count=True) \ + .limit(10) \ + .filter("name == 'doc_type'") \ + .sort(PNSortKey.asc(PNSortKeyValue.ID), PNSortKey.desc(PNSortKeyValue.UPDATED)) \ + .page(None) \ + .future() + # snippet.end + + built = envelope.result + a.eq(ids(built.data), channels, 'ascending by id') + a.eq(built.total_count, 3) + a.eq([c['custom'] for c in built.data], [{'rank': 0}, {'rank': 1}, {'rank': 2}]) + a.eq([c['description'] for c in built.data], ['Channel 0', 'Channel 1', 'Channel 2']) + + # snippet.get_all_channel_metadata_named + from pubnub.models.consumer.objects_v2.sort import PNSortKey, PNSortKeyValue + + metadata = await pubnub.get_all_channel_metadata(limit=10, + include_custom=True, + filter="name == 'doc_type'", + include_total_count=True, + sort_keys=[PNSortKey.asc(PNSortKeyValue.ID), + PNSortKey.desc(PNSortKeyValue.UPDATED)]) \ + .future() + # snippet.end + + a.eq(ids(metadata.result.data), channels, 'named arguments: same list') + a.eq(metadata.result.total_count, 3) + + plain = await listed() + a.not_contains(plain.data[0], 'custom', 'custom only when included') + a.eq(plain.data[0]['type'], 'doc') + a.eq(plain.total_count, None) + a.not_contains((await listed(include_type=False)).data[0], 'type') + a.not_contains((await listed(include_status=False)).data[0], 'status') + only = checked(await pubnub.get_all_channel_metadata( + filter="name == '%s' && id == '%s'" % (kind, channels[2])).future()) + a.eq(ids(only.result.data), [channels[2]], 'filter on name and id') + + ordered = [PNSortKey.asc(PNSortKeyValue.ID)] + first = await listed(limit=2, sort_keys=ordered) + a.eq(ids(first.data), channels[:2]) + a.ok(isinstance(first.next, Next), 'next page token') + second = await listed(limit=2, sort_keys=ordered, page=first.next) + a.eq(ids(second.data), channels[2:]) + a.ok(isinstance(second.prev, Previous), 'prev page token') + a.eq(ids((await listed(limit=2, sort_keys=ordered, page=second.prev)).data), channels[:2]) + finally: + await cleanup(pubnub, channels=channels) + + +async def test_get_channel_metadata_builder(aclients): + """Snippets: get_channel_metadata_builder, get_channel_metadata_named.""" + pubnub = aclients.asyncio('open', 'reader') + channel = 'channel_id' + record(channels=[channel]) + try: + checked(await pubnub.set_channel_metadata(channel=channel, name='Doc channel', description='About', + status='live', type='room', custom={'topic': 'docs'}).future()) + + async def topic(): + return (await channel_data(pubnub, channel, include_custom=True))['custom'] + + await settled_eq(topic, {'topic': 'docs'}, 'channel visible') + + # snippet.get_channel_metadata_builder + envelope = await pubnub.get_channel_metadata(include_custom=True) \ + .channel("channel_id") \ + .future() + # snippet.end + + data = envelope.result.data + a.eq((data['id'], data['name'], data['description']), (channel, 'Doc channel', 'About')) + a.eq((data['status'], data['type'], data['custom']), ('live', 'room', {'topic': 'docs'})) + a.eq(envelope.result.status, 200) + + # snippet.get_channel_metadata_named + metadata = await pubnub.get_channel_metadata(channel="channel_id", include_custom=True).future() + # snippet.end + + a.eq(metadata.result.data, data, 'named arguments: same object') + a.not_contains(checked(await pubnub.get_channel_metadata(channel=channel).future()).result.data, 'custom') + a.not_contains(checked(await pubnub.get_channel_metadata( + channel=channel, include_type=False).future()).result.data, 'type') + a.not_contains(checked(await pubnub.get_channel_metadata( + channel=channel, include_status=False).future()).result.data, 'status') + missing = 'doc_missing_channel' + await expect_error_async(lambda: pubnub.get_channel_metadata(channel=missing).future(), '404') + finally: + await cleanup(pubnub, channels=[channel]) + + +@pytest.mark.timeout(300) +async def test_set_channel_metadata_builder(aclients): + """Snippets: set_channel_metadata_builder, set_channel_metadata_named.""" + pubnub = aclients.asyncio('open', 'setter') + first = 'channel_id' + second = 'channel_id_named' + record(channels=[first, second]) + fields = {'name': 'Channel Name', 'description': 'Description', 'status': 'Archived', 'type': 'Archived'} + try: + seen = await watch(aclients, first) + + # snippet.set_channel_metadata_builder + envelope = await pubnub.set_channel_metadata(include_custom=True) \ + .channel("channel_id") \ + .set_name("Channel Name") \ + .set_status("Archived") \ + .set_type("Archived") \ + .description("Description") \ + .custom({"key1": "val1", "key2": "val2"}) \ + .future() + # snippet.end + + data = envelope.result.data + a.eq({k: data[k] for k in fields}, fields) + a.eq((data['id'], data['custom']), (first, {'key1': 'val1', 'key2': 'val2'})) + a.ok(data['eTag'] and data['updated'], 'eTag and updated are returned') + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['id'], payload['name']), ('channel', 'set', first, 'Channel Name')) + a.eq(payload['custom'], {'key1': 'val1', 'key2': 'val2'}) + await settled_eq(lambda: channel_data(pubnub, first, include_custom=True), data, + 'read back equals the set response') + + seen = await watch(aclients, second) + + # snippet.set_channel_metadata_named + envelope = await pubnub.set_channel_metadata(channel="channel_id_named", + name="Channel Name", + status="Archived", + type="Archived", + description="Description", + custom={"key1": "val1", "key2": "val2"}, + include_custom=True) \ + .future() + # snippet.end + + named = envelope.result.data + a.eq({k: named[k] for k in fields}, fields) + a.eq((named['id'], named['custom']), (second, {'key1': 'val1', 'key2': 'val2'})) + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['id']), ('channel', 'set', second)) + + replaced = checked(await pubnub.set_channel_metadata(channel=first, custom={'only': 'this'}, + include_custom=True).future()).result.data + a.eq(replaced['custom'], {'only': 'this'}) + + async def first_custom(): + return (await channel_data(pubnub, first, include_custom=True))['custom'] + + await settled_eq(first_custom, {'only': 'this'}, 'custom is overwritten') + light = checked(await pubnub.set_channel_metadata(channel=first, name='Channel Name', include_status=False, + include_type=False).future()).result.data + a.not_contains(light, 'status') + a.not_contains(light, 'type') + a.not_contains(light, 'custom', 'custom only when included') + + keep = dict(name='Channel Name', description='Description', status='Archived', type='Archived', + custom={'only': 'this'}) + checked(await pubnub.set_channel_metadata(channel=first, **keep).future()) + same = await watch(aclients, first) + checked(await pubnub.set_channel_metadata(channel=first, **keep).future()) + keep['description'] = 'Changed' + checked(await pubnub.set_channel_metadata(channel=first, **keep).future()) + kind, event, payload = await first_event(same) + a.eq((event, payload['description']), ('set', 'Changed'), 'unchanged data raised no event') + finally: + await cleanup(pubnub, channels=[first, second]) + + +async def test_remove_channel_metadata_builder(aclients): + """Snippets: remove_channel_metadata_builder, remove_channel_metadata_named.""" + pubnub = aclients.asyncio('open', 'remover') + first = 'channel_id' + second = 'channel_id_named' + record(channels=[first, second]) + try: + for channel in (first, second): + checked(await pubnub.set_channel_metadata(channel=channel, name='To remove').future()) + for channel in (first, second): + async def name_of(): + return (await channel_data(pubnub, channel))['name'] + + await settled_eq(name_of, 'To remove', f'{channel} visible') + seen = await watch(aclients, first) + + # snippet.remove_channel_metadata_builder + envelope = await pubnub.remove_channel_metadata() \ + .channel("channel_id") \ + .future() + # snippet.end + + a.eq(envelope.result.status, 200) + a.eq(envelope.result.data, None, 'nothing is returned') + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['id']), ('channel', 'delete', first)) + await gone(lambda: pubnub.get_channel_metadata(channel=first).future()) + + async def second_id(): + return (await channel_data(pubnub, second))['id'] + + await settled_eq(second_id, second, 'other channels stay') + + # snippet.remove_channel_metadata_named + envelope = await pubnub.remove_channel_metadata(channel="channel_id_named").future() + # snippet.end + + a.eq(envelope.result.status, 200) + await gone(lambda: pubnub.get_channel_metadata(channel=second).future()) + + async def listed_second(): + return (await attempt(lambda: pubnub.get_all_channel_metadata( + filter="id == '%s'" % second).future())).result.data + + await settled_eq(listed_second, [], 'the list no longer has the channel') + finally: + await cleanup(pubnub, channels=[first, second]) + + +async def test_get_memberships_builder(aclients): + """Snippets: get_memberships_builder, get_memberships_named.""" + pubnub = aclients.asyncio('open', 'reader') + uid = 'some_uuid' + plain = 'somechannel' + with_custom = 'somechannel_with_custom' + record([uid], [plain, with_custom]) + try: + await fresh(pubnub, [uid], [plain, with_custom]) + await seed_channels(pubnub, plain, with_custom) + await seed_memberships(pubnub, uid, plain, with_custom) + await memberships_visible(pubnub, uid, plain, with_custom) + + # snippet.get_memberships_builder + from pubnub.models.consumer.objects_v2.common import MembershipIncludes + envelope = await pubnub.get_memberships() \ + .include(MembershipIncludes(custom=True, channel=True, channel_custom=True)) \ + .uuid("some_uuid").future() + # snippet.end + + check_memberships(envelope.result.data, plain, with_custom) + a.eq(envelope.result.status, 200) + + # snippet.get_memberships_named + from pubnub.models.consumer.objects_v2.common import MembershipIncludes + + envelope = await pubnub.get_memberships(uuid="some_uuid", + include=MembershipIncludes(custom=True, channel=True, + channel_custom=True)) \ + .future() + # snippet.end + + check_memberships(envelope.result.data, plain, with_custom) + + # Details appear only when they are included + bare = await memberships_of(pubnub, uid) + a.not_contains(bare[0], 'custom', 'custom only when included') + a.eq(bare[0]['channel'], {'id': bare[0]['channel']['id']}, 'channel is only an id by default') + only_custom = await memberships_of(pubnub, uid, include=MembershipIncludes(custom=True)) + a.contains(only_custom[0], 'custom') + a.eq(by_channel(only_custom)[with_custom]['custom'], CUSTOM_2) + a.not_contains(bare[0], 'type') + a.not_contains(bare[0], 'status') + typed = PNChannelMembership(plain, status='active', type='doc') + checked(await pubnub.set_memberships(uuid=uid, channel_memberships=[typed]).future()) + + async def typed_of(): + found = await memberships_of(pubnub, uid, include=MembershipIncludes(type=True, status=True)) + return [(m['type'], m['status']) for m in found if m['channel']['id'] == plain] + + await settled_eq(typed_of, [('doc', 'active')], 'type and status of the membership') + + filtered = await memberships_of(pubnub, uid, filter="channel.name LIKE 'some name with*'") + a.eq(channel_ids(filtered), [with_custom], 'filter on the channel name') + counted = checked(await pubnub.get_memberships(uuid=uid).include_total_count(True).future()).result + a.eq(counted.total_count, 2, 'total count') + + # Paging with next and prev, sorted by the update time (the only sort key the service accepts here) + newest = [PNSortKey.desc(PNSortKeyValue.UPDATED)] + first = checked(await pubnub.get_memberships(uuid=uid, limit=1, sort_keys=newest).future()).result + a.eq(len(first.data), 1) + a.ok(isinstance(first.next, Next), 'next page token') + second = checked(await pubnub.get_memberships(uuid=uid, limit=1, sort_keys=newest, + page=first.next).future()).result + a.eq(sorted(channel_ids(first.data + second.data)), sorted([plain, with_custom]), 'two pages cover both') + a.ok(isinstance(second.prev, Previous), 'prev page token') + back = checked(await pubnub.get_memberships(uuid=uid, limit=1, sort_keys=newest, + page=second.prev).future()).result + a.eq(channel_ids(back.data), channel_ids(first.data), 'prev returns the first page') + finally: + await cleanup(pubnub, [uid], [plain, with_custom]) + + +@pytest.mark.timeout(300) +async def test_set_memberships_builder(aclients): + """Snippets: set_memberships_builder, set_memberships_named.""" + pubnub = aclients.asyncio('open', 'setter') + first = 'some_uuid' + second = 'some_uuid_named' + plain = 'somechannel' + with_custom = 'somechannel_with_custom' + record([first, second], [plain, with_custom]) + try: + await fresh(pubnub, [first, second], [plain, with_custom]) + seen = await watch(aclients, first) + + # snippet.set_memberships_builder + from pubnub.models.consumer.objects_v2.common import MembershipIncludes + from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership + some_channel = "somechannel" + some_channel_with_custom = "somechannel_with_custom" + + await pubnub.set_channel_metadata() \ + .channel(some_channel) \ + .set_name("some name") \ + .future() + + custom_1 = { + "key3": "val1", + "key4": "val2", + } + + await pubnub.set_channel_metadata() \ + .channel(some_channel_with_custom) \ + .set_name("some name with custom") \ + .custom(custom_1) \ + .future() + + custom_2 = { + "key5": "val1", + "key6": "val2", + } + + channel_memberships_to_set = [ + PNChannelMembership.channel(some_channel), + PNChannelMembership.channel_with_custom(some_channel_with_custom, custom_2), + ] + + envelope = await pubnub.set_memberships() \ + .uuid("some_uuid") \ + .channel_memberships(channel_memberships_to_set) \ + .include(MembershipIncludes(custom=True, channel=True, channel_custom=True)) \ + .future() + # snippet.end + + check_memberships(envelope.result.data, plain, with_custom) + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['uuid']['id']), ('membership', 'set', first)) + a.contains([plain, with_custom], payload['channel']['id']) + + seen = await watch(aclients, second) + + # snippet.set_memberships_named + from pubnub.models.consumer.objects_v2.common import MembershipIncludes + from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership + + some_channel = "somechannel" + some_channel_with_custom = "somechannel_with_custom" + + await pubnub.set_channel_metadata(channel=some_channel, name="some name").future() + + custom_1 = { + "key3": "val1", + "key4": "val2", + } + + await pubnub.set_channel_metadata(channel=some_channel_with_custom, + name="some name with custom", + custom=custom_1) \ + .future() + + custom_2 = { + "key5": "val1", + "key6": "val2", + } + + channel_memberships_to_set = [ + PNChannelMembership.channel(some_channel), + PNChannelMembership.channel_with_custom(some_channel_with_custom, custom_2), + ] + + envelope = await pubnub.set_memberships(uuid="some_uuid_named", + channel_memberships=channel_memberships_to_set, + include=MembershipIncludes(custom=True, channel=True, + channel_custom=True)) \ + .future() + # snippet.end + + check_memberships(envelope.result.data, plain, with_custom) + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['uuid']['id']), ('membership', 'set', second)) + + # The channel side sees the same memberships + await settled_eq(lambda: sorted_of(users_of(pubnub, plain)), sorted([first, second]), + 'both users are members') + + # Set adds to the stored memberships, it does not replace them + extra = 'somechannel_extra' + record(channels=[extra]) + try: + checked(await pubnub.set_channel_metadata(channel=extra, name='extra').future()) + added = checked(await pubnub.set_memberships( + uuid=first, channel_memberships=[PNChannelMembership.channel(extra)]).future()) + a.eq(sorted(channel_ids(added.result.data)), sorted([plain, with_custom, extra]), 'set keeps the others') + finally: + await cleanup(pubnub, [first], [extra]) + finally: + await cleanup(pubnub, [first, second], [plain, with_custom]) + + +@pytest.mark.timeout(300) +async def test_remove_memberships_builder(aclients): + """Snippets: remove_memberships_builder, remove_memberships_named.""" + pubnub = aclients.asyncio('open', 'remover') + first = 'some_uuid' + second = 'some_uuid_named' + plain = 'somechannel' + with_custom = 'somechannel_with_custom' + record([first, second], [plain, with_custom]) + try: + await fresh(pubnub, [first, second], [plain, with_custom]) + await seed_channels(pubnub, plain, with_custom) + for uid in (first, second): + await seed_memberships(pubnub, uid, plain, with_custom) + for uid in (first, second): + await settled_eq(lambda: sorted_of(channels_of(pubnub, uid)), sorted([plain, with_custom]), + f'memberships of {uid} seeded') + seen = await watch(aclients, first) + + # snippet.remove_memberships_builder + from pubnub.models.consumer.objects_v2.common import MembershipIncludes + from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership + some_channel = "somechannel" + + envelope = await pubnub.remove_memberships() \ + .uuid("some_uuid") \ + .channel_memberships([PNChannelMembership.channel(some_channel)]) \ + .include(MembershipIncludes(custom=True, channel=True, channel_custom=True)) \ + .future() + # snippet.end + + left = envelope.result.data + a.eq(channel_ids(left), [with_custom], 'the response lists the remaining memberships') + a.eq(left[0]['custom'], CUSTOM_2) + a.eq(left[0]['channel']['custom'], CUSTOM_1) + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['uuid']['id'], payload['channel']['id']), ('membership', 'delete', first, plain)) + await settled_eq(lambda: channels_of(pubnub, first), [with_custom], 'membership removed') + + async def second_count(): + return len(await memberships_of(pubnub, second)) + + await settled_eq(second_count, 2, 'other users keep theirs') + + # snippet.remove_memberships_named + from pubnub.models.consumer.objects_v2.common import MembershipIncludes + from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership + + envelope = await pubnub.remove_memberships(uuid="some_uuid_named", + channel_memberships=[PNChannelMembership.channel(some_channel)], + include=MembershipIncludes(custom=True, channel=True, + channel_custom=True)) \ + .future() + # snippet.end + + a.eq(channel_ids(envelope.result.data), [with_custom]) + a.eq(envelope.result.data[0]['channel']['custom'], CUSTOM_1) + await settled_eq(lambda: channels_of(pubnub, second), [with_custom], 'second membership removed') + + async def plain_id(): + return (await channel_data(pubnub, plain))['id'] + + await settled_eq(plain_id, plain, 'the channel stays') + finally: + await cleanup(pubnub, [first, second], [plain, with_custom]) + + +@pytest.mark.timeout(300) +async def test_manage_memberships_builder(aclients): + """Snippets: manage_memberships_builder, manage_memberships_named.""" + pubnub = aclients.asyncio('open', 'manager') + first = 'some_uuid' + second = 'some_uuid_named' + plain = 'somechannel' + with_custom = 'somechannel_with_custom' + record([first, second], [plain, with_custom]) + try: + await fresh(pubnub, [first, second], [plain, with_custom]) + await seed_channels(pubnub, plain, with_custom) + for uid in (first, second): + await seed_one_membership(pubnub, uid, with_custom) + for uid in (first, second): + await settled_eq(lambda: channels_of(pubnub, uid), [with_custom], f'seed of {uid} visible') + seen = await watch(aclients, first) + + # snippet.manage_memberships_builder + from pubnub.models.consumer.objects_v2.common import MembershipIncludes + from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership + some_channel = "somechannel" + some_channel_with_custom = "somechannel_with_custom" + + envelope = await pubnub.manage_memberships() \ + .uuid("some_uuid") \ + .set([PNChannelMembership.channel(some_channel)]) \ + .remove([PNChannelMembership.channel(some_channel_with_custom)]) \ + .include(MembershipIncludes(custom=True, channel=True, channel_custom=True)) \ + .future() + # snippet.end + + a.eq(channel_ids(envelope.result.data), [plain], 'the response lists the remaining memberships') + a.eq(envelope.result.data[0]['channel']['name'], 'some name') + kind, event, payload = await first_event(seen) + a.eq(kind, 'membership') + a.contains([('set', plain), ('delete', with_custom)], (event, payload['channel']['id'])) + await settled_eq(lambda: channels_of(pubnub, first), [plain], 'memberships changed') + + # snippet.manage_memberships_named + from pubnub.models.consumer.objects_v2.common import MembershipIncludes + from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership + + envelope = await pubnub.manage_memberships(uuid="some_uuid_named", + channel_memberships_to_set=[ + PNChannelMembership.channel(some_channel)], + channel_memberships_to_remove=[ + PNChannelMembership.channel(some_channel_with_custom)], + include=MembershipIncludes(custom=True, channel=True, + channel_custom=True)) \ + .future() + # snippet.end + + a.eq(channel_ids(envelope.result.data), [plain]) + await settled_eq(lambda: channels_of(pubnub, second), [plain], 'second user changed') + finally: + await cleanup(pubnub, [first, second], [plain, with_custom]) + + +async def test_get_channel_members_builder(aclients): + """Snippets: get_channel_members_builder, get_channel_members_named.""" + pubnub = aclients.asyncio('open', 'reader') + channel = 'channel_id' + plain = 'some_uuid' + with_custom = 'some_uuid_with_custom' + record([plain, with_custom], [channel]) + try: + await fresh(pubnub, [plain, with_custom], [channel]) + await seed_users(pubnub, plain, with_custom) + checked(await pubnub.set_channel_metadata(channel=channel, name='Doc channel').future()) + await seed_members(pubnub, channel, plain, with_custom) + await members_visible(pubnub, channel, plain, with_custom) + + # snippet.get_channel_members_builder + from pubnub.models.consumer.objects_v2.common import MemberIncludes + envelope = await pubnub.get_channel_members() \ + .channel("channel_id") \ + .include(MemberIncludes(custom=True, user=True, user_custom=True)) \ + .future() + # snippet.end + + check_members(envelope.result.data, plain, with_custom) + a.eq(envelope.result.status, 200) + + # snippet.get_channel_members_named + from pubnub.models.consumer.objects_v2.common import MemberIncludes + + envelope = await pubnub.get_channel_members(channel="channel_id", + include=MemberIncludes(custom=True, user=True, + user_custom=True)) \ + .future() + # snippet.end + + check_members(envelope.result.data, plain, with_custom) + + bare = await members_of(pubnub, channel) + a.not_contains(bare[0], 'custom', 'custom only when included') + a.eq(bare[0]['uuid'], {'id': bare[0]['uuid']['id']}, 'the user is only an id by default') + only_custom = await members_of(pubnub, channel, include=MemberIncludes(custom=True)) + a.eq(by_member(only_custom)[with_custom]['custom'], CUSTOM_2) + + # Member filters address the user as uuid.name, uuid.description is not a filter property + filtered = await members_of(pubnub, channel, filter="uuid.name LIKE 'some name with*'") + a.eq(member_ids(filtered), [with_custom], 'filter on the user name') + counted = checked(await pubnub.get_channel_members(channel=channel).include_total_count(True).future()).result + a.eq(counted.total_count, 2, 'total count') + + newest = [PNSortKey.desc(PNSortKeyValue.UPDATED)] + first = checked(await pubnub.get_channel_members(channel=channel, limit=1, sort_keys=newest).future()).result + a.eq(len(first.data), 1) + a.ok(isinstance(first.next, Next), 'next page token') + second = checked(await pubnub.get_channel_members(channel=channel, limit=1, sort_keys=newest, + page=first.next).future()).result + a.eq(sorted(member_ids(first.data + second.data)), sorted([plain, with_custom]), 'two pages cover both') + a.ok(isinstance(second.prev, Previous), 'prev page token') + back = checked(await pubnub.get_channel_members(channel=channel, limit=1, sort_keys=newest, + page=second.prev).future()).result + a.eq(member_ids(back.data), member_ids(first.data), 'prev returns the first page') + finally: + await cleanup(pubnub, [plain, with_custom], [channel]) + + +@pytest.mark.timeout(300) +async def test_set_channel_members_builder(aclients): + """Snippets: set_channel_members_builder, set_channel_members_named.""" + pubnub = aclients.asyncio('open', 'setter') + first = 'channel_id' + second = 'channel_id_named' + plain = 'some_uuid' + with_custom = 'some_uuid_with_custom' + record([plain, with_custom], [first, second]) + try: + await fresh(pubnub, [plain, with_custom, 'some_uuid_extra'], [first, second]) + seen = await watch(aclients, first) + + # snippet.set_channel_members_builder + from pubnub.models.consumer.objects_v2.channel_members import PNUserMember + from pubnub.models.consumer.objects_v2.common import MemberIncludes + await pubnub.set_uuid_metadata() \ + .uuid("some_uuid") \ + .set_name("some name") \ + .future() + + custom_1 = { + "key3": "val1", + "key4": "val2" + } + + await pubnub.set_uuid_metadata() \ + .uuid("some_uuid_with_custom") \ + .set_name("some name with custom") \ + .custom(custom_1) \ + .future() + + custom_2 = { + "key5": "val1", + "key6": "val2" + } + + uuids_to_set = [ + PNUserMember(user_id="some_uuid"), + PNUserMember(user_id="some_uuid_with_custom", custom=custom_2) + ] + + envelope = await pubnub.set_channel_members() \ + .channel("channel_id") \ + .uuids(uuids_to_set) \ + .include(MemberIncludes(custom=True, user=True, user_custom=True)) \ + .future() + # snippet.end + + check_members(envelope.result.data, plain, with_custom) + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['channel']['id']), ('membership', 'set', first)) + a.contains([plain, with_custom], payload['uuid']['id']) + + seen = await watch(aclients, second) + + # snippet.set_channel_members_named + from pubnub.models.consumer.objects_v2.common import MemberIncludes + from pubnub.models.consumer.objects_v2.channel_members import PNUserMember + + await pubnub.set_uuid_metadata(uuid="some_uuid", name="some name").future() + + custom_1 = { + "key3": "val1", + "key4": "val2" + } + + await pubnub.set_uuid_metadata(uuid="some_uuid_with_custom", + name="some name with custom", + custom=custom_1) \ + .future() + + custom_2 = { + "key5": "val1", + "key6": "val2" + } + + uuids_to_set = [ + PNUserMember(user_id="some_uuid"), + PNUserMember(user_id="some_uuid_with_custom", custom=custom_2) + ] + + envelope = await pubnub.set_channel_members(channel="channel_id_named", + uuids=uuids_to_set, + include=MemberIncludes(custom=True, user=True, + user_custom=True)) \ + .future() + # snippet.end + + check_members(envelope.result.data, plain, with_custom) + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['channel']['id']), ('membership', 'set', second)) + + await settled_eq(lambda: sorted_of(channels_of(pubnub, plain)), sorted([first, second]), + 'the user side sees both channels') + + # Set adds to the stored members, it does not replace them + extra = 'some_uuid_extra' + record(uuids=[extra]) + try: + checked(await pubnub.set_uuid_metadata(uuid=extra, name='extra').future()) + added = checked(await pubnub.set_channel_members(channel=first, uuids=[PNUserMember(user_id=extra)]).future()) + a.eq(sorted(member_ids(added.result.data)), sorted([plain, with_custom, extra]), 'set keeps the others') + finally: + await cleanup(pubnub, [extra], []) + finally: + await cleanup(pubnub, [plain, with_custom], [first, second]) + + +@pytest.mark.timeout(300) +async def test_remove_channel_members_builder(aclients): + """Snippets: remove_channel_members_builder, remove_channel_members_named.""" + pubnub = aclients.asyncio('open', 'remover') + first = 'channel_id' + second = 'channel_id_named' + plain = 'some_uuid' + with_custom = 'some_uuid_with_custom' + record([plain, with_custom], [first, second]) + try: + await fresh(pubnub, [plain, with_custom, 'some_uuid_extra'], [first, second]) + await seed_users(pubnub, plain, with_custom) + for channel in (first, second): + checked(await pubnub.set_channel_metadata(channel=channel, name='Doc channel').future()) + await seed_members(pubnub, channel, plain, with_custom) + for channel in (first, second): + await settled_eq(lambda: sorted_of(users_of(pubnub, channel)), sorted([plain, with_custom]), + f'members of {channel} seeded') + seen = await watch(aclients, first) + + # snippet.remove_channel_members_builder + from pubnub.models.consumer.objects_v2.common import MemberIncludes + from pubnub.models.consumer.objects_v2.channel_members import PNUserMember + envelope = await pubnub.remove_channel_members() \ + .channel("channel_id") \ + .uuids([PNUserMember(user_id="some_uuid")]) \ + .include(MemberIncludes(custom=True, user=True, user_custom=True)) \ + .future() + # snippet.end + + left = envelope.result.data + a.eq(member_ids(left), [with_custom], 'the response lists the remaining members') + a.eq(left[0]['custom'], CUSTOM_2) + a.eq(left[0]['uuid']['custom'], CUSTOM_1) + kind, event, payload = await first_event(seen) + a.eq((kind, event, payload['channel']['id'], payload['uuid']['id']), ('membership', 'delete', first, plain)) + await settled_eq(lambda: users_of(pubnub, first), [with_custom], 'member removed') + + async def second_count(): + return len(await members_of(pubnub, second)) + + await settled_eq(second_count, 2, 'other channels keep theirs') + + # snippet.remove_channel_members_named + from pubnub.models.consumer.objects_v2.common import MemberIncludes + from pubnub.models.consumer.objects_v2.channel_members import PNUserMember + + envelope = await pubnub.remove_channel_members(channel="channel_id_named", + uuids=[PNUserMember(user_id="some_uuid")], + include=MemberIncludes(custom=True, user=True, + user_custom=True)) \ + .future() + # snippet.end + + a.eq(member_ids(envelope.result.data), [with_custom]) + a.eq(envelope.result.data[0]['uuid']['custom'], CUSTOM_1) + await settled_eq(lambda: users_of(pubnub, second), [with_custom], 'second member removed') + + async def plain_id(): + return (await uuid_data(pubnub, plain))['id'] + + await settled_eq(plain_id, plain, 'the user stays') + finally: + await cleanup(pubnub, [plain, with_custom], [first, second]) + + +@pytest.mark.timeout(300) +async def test_manage_channel_members_builder(aclients): + """Snippets: manage_channel_members_builder, manage_channel_members_named.""" + pubnub = aclients.asyncio('open', 'manager') + first = 'channel_id' + second = 'channel_id_named' + plain = 'some_uuid' + with_custom = 'some_uuid_with_custom' + record([plain, with_custom], [first, second]) + try: + await fresh(pubnub, [plain, with_custom, 'some_uuid_extra'], [first, second]) + await seed_users(pubnub, plain, with_custom) + for channel in (first, second): + checked(await pubnub.set_channel_metadata(channel=channel, name='Doc channel').future()) + await seed_one_member(pubnub, channel, with_custom) + for channel in (first, second): + await settled_eq(lambda: users_of(pubnub, channel), [with_custom], f'seed of {channel} visible') + seen = await watch(aclients, first) + + # snippet.manage_channel_members_builder + from pubnub.models.consumer.objects_v2.channel_members import PNUserMember + from pubnub.models.consumer.objects_v2.common import MemberIncludes + envelope = await pubnub.manage_channel_members() \ + .channel("channel_id") \ + .set([PNUserMember(user_id="some_uuid")]) \ + .remove([PNUserMember(user_id="some_uuid_with_custom")]) \ + .include(MemberIncludes(custom=True, user=True, user_custom=True)) \ + .future() + # snippet.end + + a.eq(member_ids(envelope.result.data), [plain], 'the response lists the remaining members') + a.eq(envelope.result.data[0]['uuid']['name'], 'some name') + kind, event, payload = await first_event(seen) + a.eq(kind, 'membership') + a.contains([('set', plain), ('delete', with_custom)], (event, payload['uuid']['id'])) + await settled_eq(lambda: users_of(pubnub, first), [plain], 'members changed') + + # snippet.manage_channel_members_named + from pubnub.models.consumer.objects_v2.common import MemberIncludes + from pubnub.models.consumer.objects_v2.channel_members import PNUserMember + + envelope = await pubnub.manage_channel_members(channel="channel_id_named", + uuids_to_set=[PNUserMember(user_id="some_uuid")], + uuids_to_remove=[PNUserMember(user_id="some_uuid_with_custom")], + include=MemberIncludes(custom=True, user=True, + user_custom=True)) \ + .future() + # snippet.end + + a.eq(member_ids(envelope.result.data), [plain]) + await settled_eq(lambda: users_of(pubnub, second), [plain], 'second channel changed') + finally: + await cleanup(pubnub, [plain, with_custom], [first, second]) + + +async def test_pnchannelmembership_class(aclients): + """Snippet: pnchannelmembership_class.""" + pubnub = aclients.asyncio('open', 'classes') + uid = 'some_uuid' + plain = 'somechannel' + with_custom = 'somechannel_with_custom' + record([uid], [plain, with_custom]) + try: + await fresh(pubnub, [uid], [plain, with_custom, 'channel_id']) + await seed_channels(pubnub, plain, with_custom) + + # snippet.pnchannelmembership_class + from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership + membership = PNChannelMembership.channel("somechannel") + membership_with_custom = PNChannelMembership.channel_with_custom("somechannel_with_custom", + {"key5": "val1", "key6": "val2"}) + # snippet.end + + a.eq(type(membership).__name__, 'JustChannel') + a.eq(type(membership_with_custom).__name__, 'ChannelWithCustom') + a.eq(membership.to_payload_dict(), {'channel': {'id': plain}}) + a.eq(membership_with_custom.to_payload_dict(), {'channel': {'id': with_custom}, 'custom': CUSTOM_2}) + checked(await pubnub.set_memberships(uuid=uid, channel_memberships=[membership, + membership_with_custom]).future()) + + async def customs(): + found = await memberships_of(pubnub, uid, include=MembershipIncludes(custom=True)) + return {m['channel']['id']: m['custom'] for m in found} + + await settled_eq(customs, {plain: None, with_custom: CUSTOM_2}, 'memberships set from the helper objects') + finally: + await cleanup(pubnub, [uid], [plain, with_custom]) + + +async def test_pnuuid_class(aclients): + """Snippet: pnuuid_class.""" + pubnub = aclients.asyncio('open', 'classes') + channel = 'channel_id' + plain = 'some_uuid' + with_custom = 'some_uuid_with_custom' + record([plain, with_custom], [channel]) + try: + await fresh(pubnub, [plain, with_custom, 'some_uuid_extra'], [channel]) + await seed_users(pubnub, plain, with_custom) + checked(await pubnub.set_channel_metadata(channel=channel, name='Doc channel').future()) + + # snippet.pnuuid_class + from pubnub.models.consumer.objects_v2.channel_members import PNUserMember + member = PNUserMember(user_id="some_uuid") + member_with_custom = PNUserMember(user_id="some_uuid_with_custom", custom={"key5": "val1", "key6": "val2"}) + # snippet.end + + a.eq(type(member).__name__, 'PNUserMember') + a.eq(type(member_with_custom).__name__, 'PNUserMember') + a.eq(member.to_payload_dict(), {'uuid': {'id': plain}}) + a.eq(member_with_custom.to_payload_dict(), {'uuid': {'id': with_custom}, 'custom': CUSTOM_2}) + checked(await pubnub.set_channel_members(channel=channel, uuids=[member, member_with_custom]).future()) + + async def customs(): + found = await members_of(pubnub, channel, include=MemberIncludes(custom=True)) + return {m['uuid']['id']: m['custom'] for m in found} + + await settled_eq(customs, {plain: None, with_custom: CUSTOM_2}, 'members set from the helper objects') + finally: + await cleanup(pubnub, [plain, with_custom], [channel]) diff --git a/tests/live/asyncio/api_reference/test_presence.py b/tests/live/asyncio/api_reference/test_presence.py new file mode 100644 index 00000000..c9aeed86 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_presence.py @@ -0,0 +1,262 @@ +"""Docs page: presence (asyncio). Same steps as sync/presence.py with await. + +Presence needs channel tracking on the keyset. Joins of a second client are asserted, never the client's own join, +and here_now is polled with aeventually because the service reports it with a delay and caches it for 3 seconds. +""" +from support import assertions as a +from support import cleanup as live_cleanup +from support.listen import alisten +from support.wait import aeventually +from shared.presence import Printed, consistent, occupancy_of, own_occupants, present + + +async def test_here_now_builder(aclients, capsys): + """Snippet: here_now_builder.""" + pubnub = aclients.asyncio('open', 'reader') + first, second = 'my_channel', 'my_channel_2' + printed = Printed(capsys) + one = aclients.asyncio('open', 'user_one') + two = aclients.asyncio('open', 'user_two') + await alisten(one, first, second) + await alisten(two, first) + expected = {first: sorted([one.uuid, two.uuid]), second: [one.uuid]} + + async def builder(): + # snippet.here_now_builder + envelope = await pubnub.here_now() \ + .channels(["my_channel", "my_channel_2"]) \ + .include_uuids(True) \ + .future() + + if envelope.status.is_error(): + print("Error retrieving here_now data") + return + + for channel_data in envelope.result.channels: + print("---") + print(f"Channel: {channel_data.channel_name}") + print(f"Occupancy: {channel_data.occupancy}") + for occupant in channel_data.occupants: + print(f"UUID: {occupant.uuid}, State: {occupant.state}") + # snippet.end + return envelope + + async def check(): + result = await builder() + a.ok(result is not None, 'here_now returned an error') + a.eq({c: own_occupants(result, c, expected[c]) for c in expected}, expected, 'own occupants per channel') + a.eq(result.result.total_channels, 2) + consistent(result) + return result + last = await aeventually(check, what='here_now lists both clients') + text = printed.text() + a.contains(text, f'Channel: {first}\nOccupancy: {occupancy_of(last, first)}\n') + a.contains(text, f'UUID: {one.uuid}, State: None') + a.contains(text, f'Channel: {second}\nOccupancy: {occupancy_of(last, second)}\n') + + +async def test_here_now_state(aclients): + """Snippet: here_now_state.""" + pubnub = aclients.asyncio('open', 'reader') + name = 'my_channel' + one = aclients.asyncio('open', 'user_one') + await alisten(one, name) + await one.set_state().channels(name).state({'abcd': {'age': 15}}).future() + + async def read(): + # snippet.here_now_state + envelope = await pubnub.here_now() \ + .channels("my_channel") \ + .include_uuids(True) \ + .include_state(True) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + return envelope + + async def check(): + envelope = await read() + found = [(o.uuid, o.state) for c in envelope.result.channels for o in c.occupants] + a.contains(found, (one.uuid, {'abcd': {'age': 15}}), 'own occupant with state') + a.eq(envelope.result.total_channels, 1) + consistent(envelope) + await aeventually(check, what='here_now returns the state') + + +async def test_here_now_occupancy(aclients): + """Snippet: here_now_occupancy.""" + pubnub = aclients.asyncio('open', 'reader') + name = 'my_channel' + mine = ['user_one', 'user_two', 'user_three'] + for who in mine: + await alisten(aclients.asyncio('open', who), name) + + async def read(): + # snippet.here_now_occupancy + envelope = await pubnub.here_now() \ + .channels("my_channel") \ + .include_uuids(False) \ + .include_state(False) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + return envelope + + async def check(): + envelope = await read() + a.eq([(c.channel_name, c.occupants) for c in envelope.result.channels], [(name, [])], 'no user IDs') + a.ok(occupancy_of(envelope, name) >= len(mine), 'the count includes the three own occupants') + a.eq(envelope.result.total_occupancy, occupancy_of(envelope, name)) + # The count has no user IDs, so a second read with them shows that the three own clients are counted. + listed = await pubnub.here_now().channels(name).include_uuids(True).future() + a.eq(own_occupants(listed, name, mine), sorted(mine), 'own occupants listed') + await aeventually(check, what='here_now counts the three occupants') + + +async def test_here_now_groups(aclients): + """Snippet: here_now_groups.""" + pubnub = aclients.asyncio('open', 'reader') + groups = [n for n in ('cg1', 'cg2', 'cg3')] + members = [(f'grouped_{i}') for i in (1, 2, 3)] + for group, member in zip(groups, members): + await pubnub.add_channel_to_channel_group().channels([member]).channel_group(group).future() + live_cleanup.record('channel_group', group) + one = aclients.asyncio('open', 'user_one') + await alisten(one, *members) + + async def read(): + # snippet.here_now_groups + envelope = await pubnub.here_now() \ + .channel_groups(['cg1', 'cg2', 'cg3']) \ + .include_uuids(True) \ + .include_state(True) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + return envelope + + async def check(): + envelope = await read() + a.eq(sorted((c.channel_name, own_occupants(envelope, c.channel_name, [one.uuid])) + for c in envelope.result.channels), + sorted((m, [one.uuid]) for m in members), 'every channel of the groups with its occupant') + a.eq(envelope.result.total_channels, 3) + consistent(envelope) + await aeventually(check, what='here_now by channel group') + + +async def test_where_now_self(aclients): + """Snippets: where_now_self, where_now_other.""" + pubnub = aclients.asyncio('open', 'reader') + first, second = 'my_channel', 'my_channel_2' + await alisten(pubnub, first, second) + other = aclients.asyncio('open', 'some-other-uuid') + await alisten(other, first) + + async def own(): + # snippet.where_now_self + envelope = await pubnub.where_now() \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + return envelope + + async def elsewhere(): + # snippet.where_now_other + envelope = await pubnub.where_now() \ + .uuid('some-other-uuid') \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + return envelope + + async def check_own(): + a.eq(sorted((await own()).result.channels), sorted([first, second]), 'own channels') + + async def check_other(): + a.eq((await elsewhere()).result.channels, [first], 'channels of the other user ID') + await aeventually(check_own) + await aeventually(check_other) + + +async def test_set_state_builder(aclients): + """Snippets: set_state_builder, get_state_builder.""" + pubnub = aclients.asyncio('open', 'such_uuid') + reader = aclients.asyncio('open', 'reader') + channels = [n for n in ('ch1', 'ch2', 'ch3')] + await alisten(pubnub, *channels) + + # snippet.set_state_builder + my_state = { + 'age': 20 + } + envelope = await pubnub.set_state() \ + .channels(['ch1', 'ch2', 'ch3']) \ + .state(my_state) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.result.state, {'age': 20}, 'state returned by set_state') + + # snippet.get_state_builder + envelope = await pubnub.get_state() \ + .channels(['ch1', 'ch2', 'ch3']) \ + .uuid('such_uuid') \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.result.channels, {c: {'age': 20} for c in channels}, 'state per channel') + fetched = await reader.get_state().channels(channels[0]).uuid(pubnub.uuid).future() + a.eq(fetched.result.channels, {channels[0]: {'age': 20}}, 'another client reads the state') + + +async def test_set_state_groups_builder(aclients): + """Snippet: set_state_groups_builder.""" + pubnub = aclients.asyncio('open', 'such_uuid') + groups = [n for n in ('gr1', 'gr2', 'gr3')] + members = [(f'grouped_{i}') for i in (1, 2, 3)] + own = 'ch1' + for group, member in zip(groups, members): + await pubnub.add_channel_to_channel_group().channels([member]).channel_group(group).future() + live_cleanup.record('channel_group', group) + await alisten(pubnub, own, *members, groups=groups) + present([own, *members], pubnub.uuid) + # The SDK refuses a set_state() that names channel groups and no channel (PubNubException "State setter for + # channel groups is not supported yet" in sync, an error status in asyncio), so the sample below adds a + # channel next to the groups. + refusal = await pubnub.set_state().channel_groups(groups).state({'age': 20}).future() + a.ok(refusal.status.is_error(), 'set_state with only channel groups is refused') + + # snippet.set_state_groups_builder + my_state = { + 'age': 20 + } + envelope = await pubnub.set_state() \ + .channels(['ch1']) \ + .channel_groups(['gr1', 'gr2', 'gr3']) \ + .state(my_state) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + a.eq(envelope.result.state, {'age': 20}, 'state returned by set_state for groups') + own_state = await pubnub.get_state().channels(own).future() + a.eq(own_state.result.channels, {own: {'age': 20}}) + + async def group_state(): + # The presence service resolves a channel group some seconds after it was created, an error answers until then. + envelope = await pubnub.get_state().channel_groups(groups).future() + a.ok(not envelope.is_error() and envelope.result is not None, 'channel groups not resolved yet') + return envelope.result.channels + + async def read_back(): + a.eq(await group_state(), {m: {'age': 20} for m in members}, 'state read back through the channel groups') + + await aeventually(read_back, timeout=45, what='state read back through the channel groups') diff --git a/tests/live/asyncio/api_reference/test_publish.py b/tests/live/asyncio/api_reference/test_publish.py new file mode 100644 index 00000000..4765dea8 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_publish.py @@ -0,0 +1,181 @@ +"""Docs page: publish (asyncio). Same steps as sync/publish.py with await.""" +from support import assertions as a +from support import cleanup as live_cleanup +from support.listen import alisten +from support.wait import aeventually +from shared.publish import history_of, stored_has + + +async def test_publish_builder(aclients): + """Snippets: publish_builder, publish_named.""" + pubnub = aclients.asyncio('open', 'publisher') + channel = 'my_channel' + seen = await alisten(aclients.asyncio('open', 'subscriber'), channel) + + # snippet.publish_builder + envelope = await pubnub.publish() \ + .channel("my_channel") \ + .message({ + 'name': 'Alex', + 'online': True + }) \ + .custom_message_type("text-message") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + first_timetoken = envelope.result.timetoken + + # snippet.publish_named + envelope = await pubnub.publish( + channel="my_channel", + message={ + 'name': 'Sam', + 'online': False + }, + custom_message_type="text-message", + meta={'origin': 'docs'} + ).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + second_timetoken = envelope.result.timetoken + + a.timetoken(first_timetoken) + a.timetoken(second_timetoken) + await aeventually(lambda: a.eq(len(seen.messages), 2, 'messages received')) + by_token = {m.timetoken: m for m in seen.messages} + a.eq(by_token[first_timetoken].message, {'name': 'Alex', 'online': True}) + a.eq(by_token[first_timetoken].publisher, pubnub.uuid) + a.eq(by_token[first_timetoken].custom_message_type, 'text-message') + a.eq(by_token[second_timetoken].user_metadata, {'origin': 'docs'}) + + +async def test_signal_message(aclients): + """Snippet: signal_message.""" + pubnub = aclients.asyncio('open', 'signaler') + channel = 'my_channel' + seen = await alisten(aclients.asyncio('open', 'subscriber'), channel) + + # snippet.signal_message + envelope = await pubnub.signal() \ + .channel("my_channel") \ + .message("typing_on") \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + + a.timetoken(envelope.result.timetoken) + await aeventually(lambda: a.eq([s.message for s in seen.signals], ['typing_on'], 'signals received')) + a.eq(seen.messages, [], 'a signal is not a message') + + +async def test_fire_message(aclients): + """Snippet: fire_message.""" + pubnub = aclients.asyncio('open', 'firer') + channel = 'my_channel' + seen = await alisten(aclients.asyncio('open', 'subscriber'), channel) + + # snippet.fire_message + envelope = await pubnub.fire() \ + .channel("my_channel") \ + .message({'command': 'refresh'}) \ + .future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + # snippet.end + + a.timetoken(envelope.result.timetoken) + # A fired message is not replicated to subscribers. A normal publish after it proves the subscriber was listening. + await pubnub.publish().channel(channel).message('after-fire').future() + await aeventually(lambda: a.eq([m.message for m in seen.messages], ['after-fire'], 'only the later one arrived')) + + +async def test_publish_metadata(aclients): + """Snippet: publish_metadata.""" + pubnub = aclients.asyncio('open', 'publisher') + channel = 'my_channel' + seen = await alisten(aclients.asyncio('open', 'subscriber'), channel) + + # snippet.publish_metadata + envelope = await pubnub.publish()\ + .channel("my_channel")\ + .message(["hello", "there"])\ + .meta({'name': 'Alex'})\ + .future() + # handle publish result, status always present, result if successful + # envelope.status.is_error() to see if error happened + # snippet.end + + a.ok(not envelope.status.is_error(), 'status is not an error') + a.timetoken(envelope.result.timetoken) + await aeventually(lambda: a.eq(len(seen.messages), 1, 'messages received')) + a.eq(seen.messages[0].message, ['hello', 'there']) + a.eq(seen.messages[0].user_metadata, {'name': 'Alex'}) + a.eq(seen.messages[0].timetoken, envelope.result.timetoken) + + +async def test_publish_store_post(aclients): + """Snippet: publish_store_post.""" + pubnub = aclients.asyncio('open', 'publisher') + channel = 'my_channel' + seen = await alisten(aclients.asyncio('open', 'subscriber'), channel) + + # snippet.publish_store_post + stored = await pubnub.publish() \ + .channel("my_channel") \ + .message({'kept': True}) \ + .should_store(True) \ + .use_post(True) \ + .future() + if stored.is_error(): + print(f"Error: {stored.status.error_data}") + + not_stored = await pubnub.publish() \ + .channel("my_channel") \ + .message({'kept': False}) \ + .should_store(False) \ + .use_post(True) \ + .future() + if not_stored.is_error(): + print(f"Error: {not_stored.status.error_data}") + # snippet.end + + a.timetoken(stored.result.timetoken) + a.timetoken(not_stored.result.timetoken) + await aeventually(lambda: a.eq(len(seen.messages), 2, 'both messages are delivered live')) + a.eq(sorted(m.message['kept'] for m in seen.messages), [False, True], 'POST bodies arrive as JSON objects') + + await aeventually(lambda: stored_has(pubnub, channel, {'kept': True})) + a.not_contains(await history_of(pubnub, channel), {'kept': False}, 'the should_store(False) message is not stored') + live_cleanup.record('history', channel) + refused = await pubnub.publish().channel(channel).message('x' * 33000).use_post(True).future() + a.ok(refused.status.is_error(), 'POST publish of a message over 32 KiB is refused') + a.eq(refused.status.status_code, 413, 'POST publish of a message over 32 KiB') + small = await pubnub.publish().channel(channel).message('x' * 30000).use_post(True).future() + a.timetoken(small.result.timetoken) + + +async def test_fire_post(aclients): + """Snippet: fire_post.""" + pubnub = aclients.asyncio('open', 'firer') + channel = 'my_channel' + seen = await alisten(aclients.asyncio('open', 'subscriber'), channel) + + # snippet.fire_post + envelope = await pubnub.fire().channel('my_channel').message('hello there').use_post(True).future() + if envelope.is_error(): + print(f"Error: {envelope.status.error_data}") + else: + print('fire timetoken: %d' % envelope.result.timetoken) + # snippet.end + + a.timetoken(envelope.result.timetoken) + await pubnub.publish().channel(channel).message('after-fire-post').future() + await aeventually(lambda: a.contains([m.message for m in seen.messages], 'after-fire-post', 'later publish')) + a.not_contains([m.message for m in seen.messages], 'hello there', 'fired messages are not delivered') + + await aeventually(lambda: stored_has(pubnub, channel, 'after-fire-post')) + a.not_contains(await history_of(pubnub, channel), 'hello there', 'fired messages are not stored in history') + live_cleanup.record('history', channel) diff --git a/tests/live/asyncio/api_reference/test_subscribe.py b/tests/live/asyncio/api_reference/test_subscribe.py new file mode 100644 index 00000000..f93bc88a --- /dev/null +++ b/tests/live/asyncio/api_reference/test_subscribe.py @@ -0,0 +1,435 @@ +"""Docs page: subscribe (asyncio). Subscribe, Entities, Event listeners, Unsubscribe and the old-style methods.""" +from pubnub.enums import PNStatusCategory +from pubnub.models.server.subscribe import SubscribeMessage +from pubnub.models.consumer.message_actions import PNMessageAction + +from support import assertions as a +from support import cleanup as live_cleanup +from support.listen import alisten +from support.wait import PRESENCE_EVENT_TIMEOUT, aeventually +from shared.presence import not_present +from shared.subscribe import AppContextCollector, Printed, attach, connected_async as connected, texts + + +async def test_subscribe_single(aclients): + """Snippet: subscribe_single.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + name = 'my_channel' + seen = attach(pubnub) + + # snippet.subscribe_single + # single channel subscription + channel = pubnub.channel("my_channel") + t1_subscription = channel.subscription() + t1_subscription.subscribe() + # snippet.end + + a.eq(channel.name, name) + await connected(seen) + await publisher.publish().channel(name).message('hello single').future() + await aeventually(lambda: a.eq(texts(seen), ['hello single'], 'messages received')) + a.eq(seen.messages[0].channel, name) + + +async def test_subscribe_multiple(aclients): + """Snippet: subscribe_multiple.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + name = 'my_channel' + group_name = 'group-test' + grouped = 'grouped_channel' + await publisher.add_channel_to_channel_group().channels([grouped]).channel_group(group_name).future() + live_cleanup.record('channel_group', group_name) + # The join of second_user is checked below. The service emits it only if the user ID is not an occupant yet. + not_present(f'{name}.2', ['second_user']) + seen = attach(pubnub) + envelopes = [] + original_from_json = SubscribeMessage.from_json.__func__ + + def counting_from_json(cls, json_input): + if json_input.get('d') == 'second': + envelopes.append(json_input['c']) + return original_from_json(cls, json_input) + + SubscribeMessage.from_json = classmethod(counting_from_json) + try: + # snippet.subscribe_multiple + channel = "my_channel" + + # multiple channel subscription + channel_1 = pubnub.channel(channel).subscription() + channel_2 = pubnub.channel(f'{channel}.2').subscription(with_presence=True) + channel_x = pubnub.channel(f'{channel}.*').subscription(with_presence=True) + + group = pubnub.channel_group("group-test").subscription() + + subscription_set = pubnub.subscription_set([channel_1, channel_2, channel_x, group]) + + subscription_set.subscribe() + # snippet.end + + await connected(seen) + await publisher.publish().channel(name).message('plain').future() + await publisher.publish().channel(f'{name}.2').message('second').future() + await publisher.publish().channel(f'{name}.other').message('wildcard').future() + await publisher.publish().channel(grouped).message('group').future() + # The message on 'my_channel.2' matches two subscriptions: the channel itself and the wildcard + # 'my_channel.*'. The service sends one envelope per matching subscription, and for the same request the + # asyncio client got one or two of them, run to run (sync got two in every run). The SDK delivers every + # envelope it receives (pubnub/event_engine/effects.py:142 passes the whole 'm' list on, pubnub/workers.py:215 + # announces each one). The proof: copies at the listener equal envelopes received, and never more than + # the number of matching subscriptions. + matching = {f'{name}.2', f'{name}.*'} + await aeventually(lambda: a.eq(sorted(set(texts(seen))), ['group', 'plain', 'second', 'wildcard'], + 'distinct messages')) + await aeventually(lambda: a.eq({text: texts(seen).count(text) for text in set(texts(seen)) + if text != 'second'}, {'plain': 1, 'wildcard': 1, 'group': 1}, + 'messages with one matching subscription arrive once')) + await aeventually(lambda: a.eq(texts(seen).count('second'), envelopes.count(f'{name}.2'), + 'one delivery per envelope the SDK received')) + a.ok(1 <= envelopes.count(f'{name}.2') <= len(matching), 'at most one envelope per matching subscription') + second = [m for m in seen.messages if m.message == 'second'] + a.eq({m.timetoken for m in second}, {second[0].timetoken}, 'the copies are the same published message') + by_text = {m.message: m for m in seen.messages} + a.eq(by_text['plain'].channel, name) + a.eq(by_text['wildcard'].channel, f'{name}.other') + a.eq(by_text['wildcard'].subscription, f'{name}.*', 'wildcard match is reported as subscription') + a.eq(by_text['group'].channel, grouped) + a.eq(by_text['group'].subscription, group_name, 'channel group match is reported as subscription') + + other = aclients.asyncio('open', 'second_user') + await alisten(other, f'{name}.2') + await aeventually(lambda: a.contains([(p.event, p.uuid) for p in seen.presence_events + if p.channel == f'{name}.2'], + ('join', other.uuid), 'join of the second client'), + timeout=PRESENCE_EVENT_TIMEOUT) + finally: + SubscribeMessage.from_json = classmethod(original_from_json) + + +async def test_entity_channel(aclients): + """Snippets: entity_channel, entity_channel_group, entity_channel_metadata, entity_user_metadata.""" + pubnub = aclients.asyncio('open', 'subscriber') + other = aclients.asyncio('open', 'publisher') + name = 'my_channel' + group_name = 'channelGroupName' + meta_name = 'channelMetadata' + user_name = 'user_metadata' + grouped = 'grouped_channel' + seen = AppContextCollector() + pubnub.subscribed_by_suite = True + pubnub.add_listener(seen) + + # snippet.entity_channel + channel = pubnub.channel("my_channel") + # snippet.end + + # snippet.entity_channel_group + channel_group = pubnub.channel_group("channelGroupName") + # snippet.end + + # snippet.entity_channel_metadata + channel_metadata = pubnub.channel_metadata("channelMetadata") + # snippet.end + + # snippet.entity_user_metadata + user_metadata = pubnub.user_metadata("user_metadata") + # snippet.end + + a.eq((type(channel).__name__, channel.name), ('PubNubChannel', name)) + a.eq((type(channel_group).__name__, channel_group.name), ('PubNubChannelGroup', group_name)) + a.eq((type(channel_metadata).__name__, channel_metadata.name), ('PubNubChannelMetadata', meta_name)) + a.eq((type(user_metadata).__name__, user_metadata.name), ('PubNubUserMetadata', user_name)) + + await other.add_channel_to_channel_group().channels([grouped]).channel_group(group_name).future() + live_cleanup.record('channel_group', group_name) + # SDK bug: PubNubUserMetadata sets _types instead of _type, so its subscription would register the user ID as a + # channel group. Delivery for user metadata is therefore not exercised here, see the report. + pubnub.subscription_set([channel.subscription(), channel_group.subscription(), + channel_metadata.subscription()]).subscribe() + await connected(seen) + try: + await other.publish().channel(name).message('on the channel').future() + await other.publish().channel(grouped).message('through the group').future() + await other.set_channel_metadata().channel(meta_name).set_name('Entity channel').future() + await aeventually( + lambda: a.eq(sorted(texts(seen)), ['on the channel', 'through the group'], 'messages received')) + await aeventually( + lambda: a.eq([e.data['id'] for e in seen.channel_events], [meta_name], 'channel metadata event')) + finally: + await other.remove_channel_metadata().channel(meta_name).future() + + +async def test_listeners_event_specific(aclients, capsys): + """Snippet: listeners_event_specific.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + name = 'my_channel' + seen = attach(pubnub) + printed = Printed(capsys) + + # snippet.listeners_event_specific + subscription = pubnub.channel("my_channel").subscription() + + # using closure for reusable listener + def on_message(listener): + def message_callback(message): + print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n") + return message_callback + + # without closure + def on_message_action(message_action): + print(f"\033[5mMessageAction received: \n{message_action.value}\033[0m\n") + + def on_signal(listener): + def signal_callback(signal): + print(f"\033[0;36mSignal received on: {listener}: \n{signal.publisher} says: \t{signal.message}\033[0m") + return signal_callback + + subscription.on_message = on_message('message_listener') + subscription.on_message_action = on_message_action + subscription.on_signal = on_signal('signal_listener') + + subscription.subscribe() + # snippet.end + + await connected(seen) + envelope = await publisher.publish().channel(name).message('listener message').future() + await publisher.signal().channel(name).message('listener signal').future() + action = PNMessageAction().create(type='reaction', value='smile', message_timetoken=envelope.result.timetoken) + await publisher.add_message_action().channel(name).message_action(action).future() + await aeventually( + lambda: a.contains(printed.text(), 'Message received on: message_listener: \n', 'message printed')) + await aeventually(lambda: a.contains(printed.text(), 'listener message', 'message payload printed')) + await aeventually(lambda: a.contains(printed.text(), f'{publisher.uuid} says: \tlistener signal', 'signal printed')) + await aeventually(lambda: a.contains(printed.text(), 'MessageAction received: \nsmile', 'message action printed')) + + +async def test_listeners_generic(aclients, capsys): + """Snippet: listeners_generic.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + name = 'my_channel' + seen = attach(pubnub) + printed = Printed(capsys) + + # snippet.listeners_generic + from pubnub.callbacks import SubscribeCallback + + # add generic listener + class PrintListener(SubscribeCallback): + def status(self, _, status): + print(f'\033[92mPrintListener.status:\n{status.category.name}\033[0m') + + def message(self, _, message): + print(f'\033[94mPrintListener.message:\n{message.message}\033[0m') + + def presence(self, _, presence): + print(f'PrintListener.presence:\n{presence.uuid} {presence.event}s ' + f'{presence.subscription or presence.channel}\033[0m') + + def signal(self, _, signal): + print(f'PrintListener.signal:\n{signal.message} from {signal.publisher}\033[0m') + + def channel(self, _, channel): + print(f'\033[0;37mChannel Meta:\n{channel.__dict__}\033[0m') + + def uuid(self, _, uuid): + print(f'User Meta:\n{uuid.__dict__}\033[0m') + + def membership(self, _, membership): + print(f'Membership:\n{membership.__dict__}\033[0m') + + def message_action(self, _, message_action): + print(f'PrintListener.message_action {message_action}\033[0m') + + def file(self, _, file_message): + print(f' {file_message.__dict__}\033[0m') + + # The docs call subscription.add_listener(PrintListener()). The SDK then calls PrintListener.message(message) + # without the pubnub argument and raises TypeError, so the client-level add_listener is used here. + pubnub.add_listener(PrintListener()) + + subscription = pubnub.channel("my_channel").subscription() + subscription.subscribe() + # snippet.end + + await connected(seen) + await publisher.publish().channel(name).message('generic message').future() + await publisher.signal().channel(name).message('generic signal').future() + await aeventually(lambda: a.contains(printed.text(), 'PrintListener.message:\ngeneric message', 'message printed')) + await aeventually(lambda: a.contains(printed.text(), f'PrintListener.signal:\ngeneric signal from {publisher.uuid}', + 'signal printed')) + + +async def test_listeners_subscription_set(aclients, capsys): + """Snippet: listeners_subscription_set.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + names_in_set = ['my_channel', 'my_channel_2'] + group_name = 'cg_1' + grouped = 'grouped_channel' + await publisher.add_channel_to_channel_group().channels([grouped]).channel_group(group_name).future() + live_cleanup.record('channel_group', group_name) + seen = attach(pubnub) + printed = Printed(capsys) + + # snippet.listeners_subscription_set + def on_message(listener): + def message_callback(message): + print(f"\033[94mMessage received on: {listener}: \n{message.message}\033[0m\n") + return message_callback + + subscription_set = pubnub.subscription_set([ + pubnub.channel("my_channel").subscription(), + pubnub.channel("my_channel_2").subscription(), + pubnub.channel_group("cg_1").subscription() + ]) + subscription_set.on_message = on_message('set_listener') + + subscription_set.subscribe() + # snippet.end + + await connected(seen) + for target, text in zip(names_in_set + [grouped], ['first', 'second', 'third']): + await publisher.publish().channel(target).message(text).future() + for text in ['first', 'second', 'third']: + await aeventually(lambda: a.contains(printed.text(), f'Message received on: set_listener: \n{text}\x1b', text)) + + +async def test_listeners_presence(aclients, capsys): + """Snippet: listeners_presence.""" + pubnub = aclients.asyncio('open', 'subscriber') + name = 'my_channel' + seen = attach(pubnub) + printed = Printed(capsys) + + # snippet.listeners_presence + def on_presence(listener): + def presence_callback(presence): + print(f"\033[0;32mPresence received on: {listener}: \t{presence.uuid} {presence.event}s " + f"{presence.subscription or presence.channel}\033[0m") + return presence_callback + + subscription = pubnub.channel("my_channel").subscription(with_presence=True) + subscription.on_presence = on_presence('presence_listener') + + subscription.subscribe() + # snippet.end + + await connected(seen) + other = aclients.asyncio('open', 'second_user') + await alisten(other, name) + await aeventually( + lambda: a.contains(printed.text(), f'presence_listener: \t{other.uuid} joins {name}', 'join printed')) + + +async def test_listeners_status(aclients, capsys): + """Snippet: listeners_status.""" + pubnub = aclients.asyncio('open', 'subscriber') + printed = Printed(capsys) + + # snippet.listeners_status + from pubnub.pubnub_asyncio import SubscribeListener + + class PrintListener(SubscribeListener): + def status(self, pubnub, status): + print(f'Status:\n{status.__dict__}') + + def message(self, pubnub, message): + pass + + def presence(self, pubnub, presence): + pass + + listener = PrintListener() + pubnub.add_listener(listener) + # snippet.end + + pubnub.subscribed_by_suite = True + pubnub.channel("my_channel").subscription().subscribe() + await aeventually(lambda: a.contains(printed.text(), 'PNConnectedCategory', 'connected status printed')) + a.contains(printed.text(), 'Status:\n{', 'status dictionary printed') + + +async def test_unsubscribe_subscription(aclients): + """Snippet: unsubscribe_subscription.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + single, control = 'my_channel', 'ch3' + seen = attach(pubnub) + pubnub.channel(control).subscription().subscribe() + + t1_subscription = pubnub.channel(single).subscription() + t1_subscription.subscribe() + await connected(seen) + await publisher.publish().channel(single).message('before').future() + await aeventually(lambda: a.eq(texts(seen), ['before'], 'message before unsubscribe')) + + # snippet.unsubscribe_subscription + t1_subscription.unsubscribe() + # snippet.end + + await aeventually(lambda: a.eq(pubnub.get_subscribed_channels(), [control], 'channels left')) + await publisher.publish().channel(single).message('after single').future() + await publisher.publish().channel(control).message('after control').future() + await aeventually(lambda: a.contains(texts(seen), 'after control', 'the control channel still delivers')) + a.not_contains(texts(seen), 'after single', 'no message after unsubscribe') + + +async def test_unsubscribe_set(aclients): + """Snippet: unsubscribe_set.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + first, second, control = [n for n in ('ch1', 'ch2', 'ch3')] + seen = attach(pubnub) + pubnub.channel(control).subscription().subscribe() + + subscription_set = pubnub.subscription_set([ + pubnub.channel(first).subscription(), + pubnub.channel(second).subscription() + ]) + subscription_set.subscribe() + await connected(seen) + await publisher.publish().channel(first).message('before first').future() + await publisher.publish().channel(second).message('before second').future() + await aeventually( + lambda: a.eq(sorted(texts(seen)), ['before first', 'before second'], 'messages before unsubscribe')) + + # snippet.unsubscribe_set + subscription_set.unsubscribe() + # snippet.end + + await aeventually(lambda: a.eq(pubnub.get_subscribed_channels(), [control], 'channels left')) + await publisher.publish().channel(first).message('after first').future() + await publisher.publish().channel(second).message('after second').future() + await publisher.publish().channel(control).message('after control').future() + await aeventually(lambda: a.contains(texts(seen), 'after control', 'the control channel still delivers')) + a.not_contains(texts(seen), 'after first', 'no message after unsubscribe') + a.not_contains(texts(seen), 'after second', 'no message after unsubscribe') + + +async def test_unsubscribe_all(aclients): + """Snippet: unsubscribe_all.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + single, first = [n for n in ('my_channel', 'ch1')] + seen = attach(pubnub) + pubnub.channel(single).subscription().subscribe() + pubnub.subscription_set([pubnub.channel(first).subscription()]).subscribe() + await connected(seen) + a.eq(sorted(pubnub.get_subscribed_channels()), sorted([single, first])) + + # snippet.unsubscribe_all + pubnub.unsubscribe_all() + # snippet.end + + # unsubscribe_all() leaves the registry unusable (see the report), so the harness must not call it again + pubnub.subscribed_by_suite = False + await aeventually(lambda: a.eq(pubnub.get_subscribed_channels(), [], 'channels left')) + await aeventually( + lambda: a.contains(seen.categories, PNStatusCategory.PNAcknowledgmentCategory, 'leave acknowledged')) + await publisher.publish().channel(single).message('after single').future() + await publisher.publish().channel(first).message('after first').future() + a.eq(texts(seen), [], 'no message after unsubscribe_all') diff --git a/tests/live/asyncio/api_reference/test_subscribe_legacy.py b/tests/live/asyncio/api_reference/test_subscribe_legacy.py new file mode 100644 index 00000000..9da34bf1 --- /dev/null +++ b/tests/live/asyncio/api_reference/test_subscribe_legacy.py @@ -0,0 +1,598 @@ +"""Docs page: subscribe-legacy (asyncio). The samples of the legacy page.""" +import io +import sys +from logging import DEBUG, getLogger + +from pubnub.enums import PNStatusCategory +from pubnub.models.consumer.message_actions import PNMessageAction + +from support import assertions as a +from support import cleanup as live_cleanup +from support.clients import BaseClients +from support.env import use_open_keys +from support.listen import Collector, alisten +from support.wait import PRESENCE_EVENT_TIMEOUT, PRESENCE_TIMEOUT, aeventually +from shared.presence import not_present +from shared.subscribe import Printed, attach, attach_status, connected_async as connected, texts + + +async def test_subscribe_old_channel(aclients): + """Snippet: subscribe_old_channel.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + name = 'my_channel' + seen = attach_status(pubnub) + + # snippet.subscribe_old_channel + pubnub.subscribe() \ + .channels('my_channel') \ + .execute() + # snippet.end + + await connected(seen) + connect = [s for s in seen.statuses if s.category == PNStatusCategory.PNConnectedCategory][0] + a.ok(not connect.is_error(), 'connected status is not an error') + a.eq(connect.error_data, None) + envelope = await publisher.publish().channel(name).message({'hello': 'old'}).meta({'k': 'v'}).future() + await publisher.signal().channel(name).message('old signal').future() + await aeventually(lambda: a.eq(len(seen.messages), 1, 'messages received')) + await aeventually(lambda: a.eq(len(seen.signals), 1, 'signals received')) + message = seen.messages[0] + a.eq((message.message, message.channel, message.subscription), ({'hello': 'old'}, name, None)) + a.eq((message.timetoken, message.user_metadata, message.publisher), + (envelope.result.timetoken, {'k': 'v'}, publisher.uuid)) + signal = seen.signals[0] + a.eq((signal.message, signal.channel, signal.publisher, signal.timetoken > 0), + ('old signal', name, publisher.uuid, True)) + + +async def test_subscribe_old_multiple(aclients): + """Snippet: subscribe_old_multiple.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + both = ['my_channel1', 'my_channel2'] + seen = attach(pubnub) + + # snippet.subscribe_old_multiple + pubnub.subscribe() \ + .channels(["my_channel1", "my_channel2"]) \ + .execute() + # snippet.end + + await connected(seen) + for target in both: + await publisher.publish().channel(target).message(f'to {target}').future() + await aeventually(lambda: a.eq(sorted(texts(seen)), sorted(f'to {t}' for t in both), 'both channels deliver')) + + +async def test_subscribe_old_wildcard(aclients): + """Snippet: subscribe_old_wildcard.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + matching = f"foo.{'bar'}" + seen = attach(pubnub) + + # snippet.subscribe_old_wildcard + pubnub.subscribe() \ + .channels("foo.*") \ + .execute() + # snippet.end + + await connected(seen) + await publisher.publish().channel(matching).message('wildcard hit').future() + await aeventually(lambda: a.contains(texts(seen), 'wildcard hit', 'wildcard delivers')) + hit = [m for m in seen.messages if m.message == 'wildcard hit'][0] + a.eq((hit.channel, hit.subscription), (matching, 'foo.*')) + + +async def test_subscribe_old_group(aclients): + """Snippet: subscribe_old_group.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + group_name = 'awesome_channel_group' + grouped = 'grouped_channel' + await publisher.add_channel_to_channel_group().channels([grouped]).channel_group(group_name).future() + live_cleanup.record('channel_group', group_name) + seen = attach(pubnub) + + # snippet.subscribe_old_group + pubnub.subscribe() \ + .channel_groups("awesome_channel_group") \ + .execute() + # snippet.end + + await connected(seen) + await publisher.publish().channel(grouped).message('group hit').future() + await aeventually(lambda: a.eq(texts(seen), ['group hit'], 'group delivers')) + a.eq((seen.messages[0].channel, seen.messages[0].subscription), (grouped, group_name)) + + +async def test_subscribe_old_presence(aclients): + """Snippets: subscribe_old_presence, subscribe_old_group_presence.""" + pubnub = aclients.asyncio('open', 'subscriber') + name = 'my_channel' + group_name = 'awesome_channel_group' + grouped = 'grouped_channel' + await aclients.asyncio('open', 'publisher').add_channel_to_channel_group().channels([grouped]) \ + .channel_group(group_name).future() + live_cleanup.record('channel_group', group_name) + # A join is emitted only for a user ID that is not an occupant yet (an earlier test can leave one listed). + not_present(name, ['second_user']) + not_present(grouped, ['member_user']) + seen = attach(pubnub) + + # snippet.subscribe_old_presence + pubnub.subscribe()\ + .channels("my_channel")\ + .with_presence()\ + .execute() + # snippet.end + + # snippet.subscribe_old_group_presence + pubnub.subscribe() \ + .channel_groups("awesome_channel_group") \ + .with_presence() \ + .execute() + # snippet.end + + await connected(seen) + other = aclients.asyncio('open', 'second_user') + await alisten(other, name) + await aeventually(lambda: a.contains([(p.event, p.channel) for p in seen.presence_events if p.uuid == other.uuid], + ('join', name), 'join on the channel'), timeout=PRESENCE_EVENT_TIMEOUT) + # Presence of a channel group is announced per member channel: a client that subscribes to the group itself + # produces no join, a client that subscribes to a member channel does, and the event carries the group in + # `subscription` (workers.py _process_incoming_payload, subscription_match with the -pnpres suffix stripped). + member = aclients.asyncio('open', 'member_user') + await alisten(member, grouped) + await aeventually(lambda: a.contains([(p.event, p.channel, p.subscription) for p in seen.presence_events + if p.uuid == member.uuid], + ('join', grouped, group_name), 'join of a member channel through the group'), + timeout=PRESENCE_EVENT_TIMEOUT) + join = [p for p in seen.presence_events if p.event == 'join' and p.uuid == other.uuid and p.channel == name][0] + a.ok(isinstance(join.timestamp, int) and join.occupancy >= 1, 'join carries timestamp and occupancy') + + +async def test_subscribe_old_state(aclients): + """Snippet: subscribe_old_state.""" + pubnub = aclients.asyncio('open', 'subscriber') + name = 'my_channel' + + # snippet.subscribe_old_state + import asyncio + from pubnub.enums import PNStatusCategory + from pubnub.pubnub_asyncio import SubscribeListener + + class MySubscribeListener(SubscribeListener): + def status(self, pubnub, status): + if status.category == PNStatusCategory.PNConnectedCategory: + state = { + 'field_a': 'awesome', + 'field_b': 10 + } + asyncio.ensure_future( + pubnub.set_state() + .channels('my_channel') + .state(state) + .future() + ) + + def message(self, pubnub, message): + pass + + def presence(self, pubnub, presence): + pass + + pubnub.add_listener(MySubscribeListener()) + pubnub.subscribe().channels("my_channel").execute() + # snippet.end + + pubnub.subscribed_by_suite = True + reader = aclients.asyncio('open', 'reader') + + async def check_state(): + fetched = await reader.get_state().channels(name).uuid(pubnub.uuid).future() + a.eq(fetched.result.channels, {name: {'field_a': 'awesome', 'field_b': 10}}, 'state set from the callback') + + await aeventually(check_state) + + async def listed_with_state(): + here = (await reader.here_now().channels(name).include_state(True).future()).result + # Other user IDs can still be listed on the shared channel, so only the own occupant is checked. + a.contains([(o.uuid, o.state) for o in here.channels[0].occupants], + (pubnub.uuid, {'field_a': 'awesome', 'field_b': 10})) + await aeventually(listed_with_state, timeout=PRESENCE_TIMEOUT, what='here_now lists the state') + + +def test_subscribe_old_logging(caplog, monkeypatch): + """Snippet: subscribe_old_logging. + + A plain (not async) test, because the sample calls asyncio.run() itself. DEBUG logs carry every request URL with + the keys. The handler of the sample writes to a buffer that replaces sys.stderr, the caplog handler takes DEBUG + records for the assertions only, and the report handler stays at the INFO level of pytest.ini. + """ + logger = getLogger('pubnub') + handlers = list(logger.handlers) + sample_stderr = io.StringIO() + monkeypatch.setattr(sys, 'stderr', sample_stderr) + caplog.set_level(DEBUG, logger='pubnub') + try: + # snippet.subscribe_old_logging + import asyncio + import logging + import pubnub + from pubnub.pnconfiguration import PNConfiguration + from pubnub.pubnub_asyncio import PubNubAsyncio, SubscribeListener + + pubnub.set_stream_logger('pubnub', logging.DEBUG) + + pnconfig = PNConfiguration() + pnconfig.subscribe_key = 'demo' + pnconfig.publish_key = 'demo' + # snippet.hide + use_open_keys(pnconfig) + # snippet.show + pnconfig.user_id = 'my_user_id' + + async def main(): + client = PubNubAsyncio(pnconfig) + client.add_listener(SubscribeListener()) + client.subscribe().channels("my_channel").execute() + + # Keep the loop running so the subscription can receive messages. + await asyncio.sleep(5) + await client.stop() + + asyncio.run(main()) + # snippet.end + records = [r for r in caplog.records if r.name == 'pubnub' and r.levelno == DEBUG] + a.ok(any('/v2/subscribe/' in r.getMessage() for r in records), 'a DEBUG record of the subscribe request') + a.ok('[DEBUG]' in sample_stderr.getvalue() and '/v2/subscribe/' in sample_stderr.getvalue(), + 'the stream handler of set_stream_logger writes the subscribe request') + finally: + for handler in logger.handlers: + if handler not in handlers: + logger.removeHandler(handler) + # The asyncio client sends no leave on stop, so my_user_id would stay an occupant of my_channel. + BaseClients.send_leaves([('open', 'my_user_id', ['my_channel'], [])]) + + +async def test_listeners_old_add(aclients, capsys): + """Snippet: listeners_old_add.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + name = 'my_channel' + printed = Printed(capsys) + seen = attach(pubnub) + + # snippet.listeners_old_add + from pubnub.callbacks import SubscribeCallback + from pubnub.enums import PNOperationType, PNStatusCategory + + class MySubscribeCallback(SubscribeCallback): + def message(self, pubnub, message): + print("Message channel: %s" % message.channel) + print("Message subscription: %s" % message.subscription) + print("Message timetoken: %s" % message.timetoken) + print("Message payload: %s" % message.message) + print("Message publisher: %s" % message.publisher) + + def presence(self, pubnub, presence): + # Can be join, leave, state-change, timeout, or interval + print("Presence event: %s" % presence.event) + + # The channel to which the message was published + print("Presence channel: %s" % presence.channel) + + # Number of users subscribed to the channel + print("Presence occupancy: %s" % presence.occupancy) + + # User state + print("Presence state: %s" % presence.state) + + # Channel group or wildcard subscription match, if any + print("Presence subscription: %s" % presence.subscription) + + # UUID to which this event is related + print("Presence UUID: %s" % presence.uuid) + + # Publish timetoken + print("Presence timestamp: %s" % presence.timestamp) + + # Current timetoken + print("Presence timetoken: %s" % presence.timetoken) + + # List of users that have joined the channel (if event is 'interval') + print("Presence joined: %s" % presence.join) + + # List of users that have left the channel (if event is 'interval') + print("Presence left: %s" % presence.leave) + + # List of users that have timed-out off the channel (if event is 'interval') + print("Presence timed out: %s" % presence.timeout) + + def status(self, pubnub, status): + # The status object returned is always related to subscribe but could contain + # information about subscribe, heartbeat, or errors + # use the operationType to switch on different options + if status.operation == PNOperationType.PNSubscribeOperation \ + or status.operation == PNOperationType.PNUnsubscribeOperation: + if status.category == PNStatusCategory.PNConnectedCategory: + pass + # This is expected for a subscribe, this means there is no error or issue whatsoever + elif status.category == PNStatusCategory.PNReconnectedCategory: + pass + # This usually occurs if subscribe temporarily fails but reconnects. This means + # there was an error but there is no longer any issue + elif status.category == PNStatusCategory.PNDisconnectedCategory: + pass + # This is the expected category for an unsubscribe. This means there + # was no error in unsubscribing from everything + elif status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: + pass + # This is usually an issue with the internet connection, this is an error, handle + # appropriately retry will be called automatically + elif status.category == PNStatusCategory.PNAccessDeniedCategory: + pass + # This means that Access Manager does not allow this client to subscribe to this + # channel and channel group configuration. This is another explicit error + else: + pass + # This is usually an issue with the internet connection, this is an error, handle appropriately + # retry will be called automatically + else: + pass + # Encountered unknown status type + + def signal(self, pubnub, signal): + print("Signal channel: %s" % signal.channel) + print("Signal subscription: %s" % signal.subscription) + print("Signal timetoken: %s" % signal.timetoken) + print("Signal payload: %s" % signal.message) + print("Signal publisher: %s" % signal.publisher) + + def message_action(self, pubnub, message_action): + print("Message action type: %s" % message_action.type) + print("Message action value: %s" % message_action.value) + print("Message action uuid: %s" % message_action.uuid) + print("Message action action_timetoken: %s" % message_action.action_timetoken) + print("Message action message_timetoken: %s" % message_action.message_timetoken) + + pubnub.add_listener(MySubscribeCallback()) + # snippet.end + + pubnub.subscribe().channels(name).with_presence().execute() + await connected(seen) + envelope = await publisher.publish().channel(name).message({'n': 1}).future() + await publisher.signal().channel(name).message('sig').future() + action = PNMessageAction().create(type='reaction', value='smile', message_timetoken=envelope.result.timetoken) + await publisher.add_message_action().channel(name).message_action(action).future() + other = aclients.asyncio('open', 'second_user') + await alisten(other, name) + for text in (f'Message channel: {name}', "Message payload: {'n': 1}", f'Message publisher: {publisher.uuid}', + f'Message timetoken: {envelope.result.timetoken}', 'Signal payload: sig', + 'Message action type: reaction', 'Message action value: smile', + f'Message action message_timetoken: {envelope.result.timetoken}', + 'Presence event: join', f'Presence channel: {name}', f'Presence UUID: {other.uuid}'): + await aeventually(lambda: a.contains(printed.text(), text, 'printed by the docs listener')) + a.ok(len(seen.messages) == 1) + + +async def test_listeners_old_remove(aclients): + """Snippet: listeners_old_remove.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + name = 'my_channel' + keeper = attach(pubnub) + + class MySubscribeCallback(Collector): + pass + + # snippet.listeners_old_remove + my_listener = MySubscribeCallback() + + pubnub.add_listener(my_listener) + + # some time later + pubnub.remove_listener(my_listener) + # snippet.end + + pubnub.add_listener(my_listener) + pubnub.subscribe().channels(name).execute() + await connected(keeper) + await publisher.publish().channel(name).message('first').future() + await aeventually(lambda: a.eq(texts(keeper), ['first'], 'the kept listener receives')) + await aeventually(lambda: a.eq(texts(my_listener), ['first'], 'a listener that is added receives')) + pubnub.remove_listener(my_listener) + await publisher.publish().channel(name).message('second').future() + await aeventually(lambda: a.eq(texts(keeper), ['first', 'second'], 'the kept listener still receives')) + a.eq(texts(my_listener), ['first'], 'a removed listener receives nothing more') + + +async def test_listeners_old_disconnects(aclients, caplog): + """Snippet: listeners_old_disconnects.""" + pubnub = aclients.asyncio('open', 'subscriber') + seen = attach(pubnub) + + # snippet.listeners_old_disconnects + import logging + + from pubnub.callbacks import SubscribeCallback + from pubnub.enums import PNStatusCategory + + logger = logging.getLogger(__name__) + + class HandleDisconnectsCallback(SubscribeCallback): + def status(self, pubnub, status): + if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: + # internet got lost, do some magic and call reconnect when ready + pubnub.reconnect() + elif status.category == PNStatusCategory.PNTimeoutCategory: + # do some magic and call reconnect when ready + pubnub.reconnect() + else: + logger.debug(status) + + def presence(self, pubnub, presence): + pass + + def message(self, pubnub, message): + pass + + def signal(self, pubnub, signal): + pass + + disconnect_listener = HandleDisconnectsCallback() + + pubnub.add_listener(disconnect_listener) + # snippet.end + + with caplog.at_level(logging.DEBUG): + pubnub.subscribe().channels('my_channel').execute() + await connected(seen) + await aeventually(lambda: a.ok( + any('PNConnectedCategory' in r.getMessage() or 'PNStatus' in r.getMessage() + for r in caplog.records if r.name == __name__ or r.name.endswith('subscribe')), + 'the docs logger saw the connected status')) + + +async def test_unsubscribe_old_channel(aclients): + """Snippet: unsubscribe_old_channel.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + single, control = 'my_channel', 'ch3' + seen = attach(pubnub) + # The observer must see joins, which the service emits only for user IDs that are not occupants yet. + not_present(single, ['subscriber', 'sentinel', 'beating_subscriber', 'quiet_subscriber']) + observer = await alisten(aclients.asyncio('open', 'observer'), single, presence=True) + pubnub.subscribe().channels([single, control]).execute() + await connected(seen) + await publisher.publish().channel(single).message('before').future() + await aeventually(lambda: a.eq(texts(seen), ['before'], 'message before unsubscribe')) + await aeventually(lambda: a.contains([(p.event, p.uuid) for p in observer.presence_events], + ('join', pubnub.uuid), 'the observer sees the join'), + timeout=PRESENCE_EVENT_TIMEOUT) + + # snippet.unsubscribe_old_channel + pubnub.unsubscribe() \ + .channels("my_channel") \ + .execute() + # snippet.end + + await aeventually(lambda: a.eq(pubnub.get_subscribed_channels(), [control], 'channels left')) + await publisher.publish().channel(single).message('after single').future() + await publisher.publish().channel(control).message('after control').future() + await aeventually(lambda: a.contains(texts(seen), 'after control', 'the control channel still delivers')) + a.not_contains(texts(seen), 'after single', 'no message after unsubscribe') + + # Documented: the default client sends a leave request when it unsubscribes, also without presence heartbeats, + # so the other subscribers see the leave event. + await aeventually(lambda: a.contains([(p.event, p.uuid) for p in observer.presence_events], + ('leave', pubnub.uuid), 'the observer sees the leave of the default client'), + timeout=PRESENCE_EVENT_TIMEOUT) + + # Documented: with suppress_leave_events the client sends no leave request. The sentinel is the join of a client + # that subscribes after the unsubscribe: the observer has received a later event on the same channel, so a leave + # that had been sent would be in its list by now. + quiet = aclients.asyncio('open', 'quiet_subscriber') + quiet.config.suppress_leave_events = True + quiet_seen = attach(quiet) + quiet.subscribe().channels(single).execute() + await connected(quiet_seen) + await aeventually(lambda: a.contains([(p.event, p.uuid) for p in observer.presence_events], + ('join', quiet.uuid), 'the observer sees the join of the quiet client'), + timeout=PRESENCE_EVENT_TIMEOUT) + quiet.unsubscribe().channels(single).execute() + sentinel = aclients.asyncio('open', 'sentinel') + await alisten(sentinel, single) + await aeventually(lambda: a.contains([(p.event, p.uuid) for p in observer.presence_events], + ('join', sentinel.uuid), 'the observer sees the later sentinel join'), + timeout=PRESENCE_EVENT_TIMEOUT) + a.not_contains([(p.event, p.uuid) for p in observer.presence_events], ('leave', quiet.uuid), + 'no leave event with suppress_leave_events') + + # Documented: with enable_presence_heartbeat and a heartbeat interval above 0 the client sends the leave. + beating = aclients.asyncio('open', 'beating_subscriber') + beating.config.enable_presence_heartbeat = True + beating.config.set_presence_timeout(20) + a.ok(beating.config.heartbeat_interval > 0, 'heartbeat interval is above 0') + beating_seen = attach(beating) + beating.subscribe().channels([single, control]).execute() + await connected(beating_seen) + await aeventually(lambda: a.contains([(p.event, p.uuid) for p in observer.presence_events], + ('join', beating.uuid), 'the observer sees the join of the heartbeat client'), + timeout=PRESENCE_EVENT_TIMEOUT) + beating.unsubscribe() \ + .channels(single) \ + .execute() + await aeventually(lambda: a.contains([(p.event, p.uuid) for p in observer.presence_events], + ('leave', beating.uuid), 'leave event with the presence heartbeat enabled')) + leave = [p for p in observer.presence_events if p.event == 'leave' and p.uuid == beating.uuid][0] + a.ok(isinstance(leave.timestamp, int) and isinstance(leave.occupancy, int), 'leave carries timestamp, occupancy') + + +async def test_unsubscribe_old_multiple(aclients): + """Snippets: unsubscribe_old_multiple, unsubscribe_old_group.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + both = ['my_channel1', 'my_channel2'] + groups = ['my_group1', 'my_group2'] + control = 'ch3' + grouped = ['grouped_one', 'grouped_two'] + for group_name, channel_name in zip(groups, grouped): + await publisher.add_channel_to_channel_group().channels([channel_name]).channel_group(group_name).future() + live_cleanup.record('channel_group', group_name) + seen = attach(pubnub) + pubnub.subscribe().channels(both + [control]).channel_groups(groups).execute() + await connected(seen) + for target in both + grouped: + await publisher.publish().channel(target).message(f'before {target}').future() + await aeventually(lambda: a.eq(len(seen.messages), 4, 'messages before unsubscribe')) + + # snippet.unsubscribe_old_multiple + pubnub.unsubscribe() \ + .channels(["my_channel1", "my_channel2"]) \ + .execute() + # snippet.end + + # snippet.unsubscribe_old_group + pubnub.unsubscribe() \ + .channel_groups(["my_group1", "my_group2"]) \ + .execute() + # snippet.end + + await aeventually(lambda: a.eq((pubnub.get_subscribed_channels(), pubnub.get_subscribed_channel_groups()), + ([control], []), 'subscriptions left')) + for target in both + grouped + [control]: + await publisher.publish().channel(target).message(f'after {target}').future() + await aeventually(lambda: a.contains(texts(seen), f'after {control}', 'the control channel still delivers')) + a.eq(sorted(m for m in texts(seen) if m.startswith('after')), [f'after {control}'], 'nothing else after') + + +async def test_unsubscribe_all_old(aclients): + """Snippet: unsubscribe_all_old.""" + pubnub = aclients.asyncio('open', 'subscriber') + publisher = aclients.asyncio('open', 'publisher') + single = 'my_channel' + group_name = 'my_group1' + grouped = 'grouped_one' + await publisher.add_channel_to_channel_group().channels([grouped]).channel_group(group_name).future() + live_cleanup.record('channel_group', group_name) + seen = attach(pubnub) + pubnub.subscribe().channels(single).channel_groups(group_name).execute() + await connected(seen) + a.eq((pubnub.get_subscribed_channels(), pubnub.get_subscribed_channel_groups()), ([single], [group_name])) + + # snippet.unsubscribe_all_old + pubnub.unsubscribe_all() + # snippet.end + + # unsubscribe_all() leaves the registry unusable (see the report), so the harness must not call it again + pubnub.subscribed_by_suite = False + await aeventually(lambda: a.eq((pubnub.get_subscribed_channels(), pubnub.get_subscribed_channel_groups()), ([], []), + 'subscriptions left')) + await aeventually( + lambda: a.contains(seen.categories, PNStatusCategory.PNAcknowledgmentCategory, 'leave acknowledged')) + await publisher.publish().channel(single).message('after single').future() + await publisher.publish().channel(grouped).message('after group').future() + a.eq(texts(seen), [], 'no message after unsubscribe_all') diff --git a/tests/live/cli.py b/tests/live/cli.py new file mode 100644 index 00000000..a43399d2 --- /dev/null +++ b/tests/live/cli.py @@ -0,0 +1,83 @@ +"""Command line of the live tier. Run from anywhere: python -u tests/live/cli.py + + lint offline checks: compile, marker lint, self-test, manifest --check, groups --check, + exceptions shape, resources shape. No keys, no network. + manifest [--check] write or check coverage.json + groups --check group consistency (also part of lint) + groups --matrix [name] the CI job matrix as JSON ("all" or empty: every group) + docs-check [] [--report-only] [--allow-ref ] [--verbose] + classify every docs embed from pubnub/python + extractor --regen regenerate the extractor fixtures from the docs function + parity ids that exist in one docset only, per page + env which roles have keys (never prints a value) + janitor [--role open|pam] clean the listed resources (NEEDS KEYS AND NETWORK) + preflight keyset feature check (NEEDS KEYS AND NETWORK) + +The tests themselves run with pytest from this folder (testpaths only apply when pytest runs in its rootdir): + cd tests/live && python -u -m pytest +""" +import compileall +import re +import sys +from pathlib import Path + +LIVE_DIR = Path(__file__).resolve().parent +sys.path.insert(0, str(LIVE_DIR)) + +from support import env, groups, lint_markers, lint_selftest, manifest, resources # noqa: E402 + + +def _compile(): + ok = compileall.compile_dir(str(LIVE_DIR), quiet=1, rx=re.compile(r'__pycache__')) + print('compile:', 'ok' if ok else 'FAILED') + return 0 if ok else 1 + + +def lint(argv): + rc = _compile() + rc |= lint_markers.main(argv) + rc |= lint_selftest.main() + rc |= manifest.main(['--check']) + rc |= groups.main(['--check']) + problems = resources.problems() + for p in problems: + print('resources:', p) + print(f'resources: {len(resources.all_names())} names, {len(problems)} problems') + rc |= 1 if problems else 0 + print('lint:', 'ok' if rc == 0 else 'FAILED') + return rc + + +def main(argv): + cmd, rest = (argv[0], argv[1:]) if argv else ('', []) + if cmd == 'lint': + return lint(rest) + if cmd == 'manifest': + return manifest.main(rest) + if cmd == 'groups': + return groups.main(rest) + if cmd == 'docs-check': + from support import docs_check + return docs_check.main(rest) + if cmd == 'extractor' and '--regen' in rest: + from support import extractor + return extractor.regen(rest[rest.index('--regen') + 1]) + if cmd == 'parity': + for line in lint_markers.parity(): + print(line) + return 0 + if cmd == 'env': + print('\n'.join(env.status())) + return 0 + if cmd == 'janitor': + from support import janitor + return janitor.main(rest) + if cmd == 'preflight': + from support import preflight + return preflight.main(rest) + print(__doc__) + return 2 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tests/live/conftest.py b/tests/live/conftest.py new file mode 100644 index 00000000..d0de24ad --- /dev/null +++ b/tests/live/conftest.py @@ -0,0 +1,10 @@ +"""Root conftest of the live tier. Thin: the hooks and fixtures live in support/hooks.py.""" +import sys +from pathlib import Path + +# "import support" and "import shared" work without pythonpath too (for example under -p no:python_path). +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import support # noqa: E402,F401 (puts the repository root first on the import path) + +pytest_plugins = ['support.hooks', 'support.explain'] diff --git a/tests/live/coverage.json b/tests/live/coverage.json new file mode 100644 index 00000000..53bf515f --- /dev/null +++ b/tests/live/coverage.json @@ -0,0 +1,1801 @@ +{ + "$comment": "GENERATED by python -u tests/live/cli.py manifest from the markers in tests/live. DO NOT EDIT. One entry per snippet id per file. Deliberate exceptions live in snippet-exceptions.json.", + "files": { + "tests/live/asyncio/api_reference/test_access_manager.py": { + "grant_token_builder": { + "test": "asyncio/api_reference/test_access_manager.py::test_grant_token_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_categories": { + "test": "asyncio/api_reference/test_access_manager.py::test_grant_token_categories", + "role": "pam", + "mode": "live" + }, + "grant_token_multi": { + "test": "asyncio/api_reference/test_access_manager.py::test_grant_token_multi", + "role": "pam", + "mode": "live" + }, + "grant_token_multi_regex": { + "test": "asyncio/api_reference/test_access_manager.py::test_grant_token_multi", + "role": "pam", + "mode": "live" + }, + "grant_token_regex": { + "test": "asyncio/api_reference/test_access_manager.py::test_grant_token_multi", + "role": "pam", + "mode": "live" + }, + "parse_token": { + "test": "asyncio/api_reference/test_access_manager.py::test_grant_token_builder", + "role": "pam", + "mode": "live" + }, + "parse_token_categories": { + "test": "asyncio/api_reference/test_access_manager.py::test_grant_token_categories", + "role": "pam", + "mode": "live" + }, + "revoke_token": { + "test": "asyncio/api_reference/test_access_manager.py::test_revoke_token", + "role": "pam", + "mode": "live" + }, + "set_token": { + "test": "asyncio/api_reference/test_access_manager.py::test_set_token", + "role": "pam", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_access_manager_legacy.py": { + "grant_token_spaces_builder": { + "test": "asyncio/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_spaces_multi": { + "test": "asyncio/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_spaces_multi_regex": { + "test": "asyncio/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_spaces_regex": { + "test": "asyncio/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_access_manager_v2.py": { + "grant_application_level": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_subkey_all", + "role": "pam", + "mode": "live" + }, + "grant_categories": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_categories", + "role": "pam", + "mode": "live" + }, + "grant_channel_all_users": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_channel_all_users", + "role": "pam", + "mode": "live" + }, + "grant_channel_auth": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_channel_auth", + "role": "pam", + "mode": "live" + }, + "grant_channel_group": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_channel_group", + "role": "pam", + "mode": "live" + }, + "grant_channel_level": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_channel_all_users", + "role": "pam", + "mode": "live" + }, + "grant_channel_ro_auth": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_channel_ro_auth", + "role": "pam", + "mode": "live" + }, + "grant_multiple_channels": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_multiple_channels", + "role": "pam", + "mode": "live" + }, + "grant_presence": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_presence", + "role": "pam", + "mode": "live" + }, + "grant_subkey_all": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_subkey_all", + "role": "pam", + "mode": "live" + }, + "grant_user_level": { + "test": "asyncio/api_reference/test_access_manager_v2.py::test_grant_channel_ro_auth", + "role": "pam", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_channel_groups.py": { + "add_channels_builder": { + "test": "asyncio/api_reference/test_channel_groups.py::test_add_channels_builder", + "role": "open", + "mode": "live" + }, + "add_channels_named": { + "test": "asyncio/api_reference/test_channel_groups.py::test_add_channels_builder", + "role": "open", + "mode": "live" + }, + "delete_channel_group_builder": { + "test": "asyncio/api_reference/test_channel_groups.py::test_delete_channel_group_builder", + "role": "open", + "mode": "live" + }, + "list_channels_builder": { + "test": "asyncio/api_reference/test_channel_groups.py::test_list_channels_builder", + "role": "open", + "mode": "live" + }, + "list_channels_named": { + "test": "asyncio/api_reference/test_channel_groups.py::test_list_channels_builder", + "role": "open", + "mode": "live" + }, + "remove_channels_builder": { + "test": "asyncio/api_reference/test_channel_groups.py::test_remove_channels_builder", + "role": "open", + "mode": "live" + }, + "remove_channels_named": { + "test": "asyncio/api_reference/test_channel_groups.py::test_remove_channels_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_configuration.py": { + "configuration_full": { + "test": "asyncio/api_reference/test_configuration.py::test_configuration_full", + "role": "open", + "mode": "live" + }, + "get_filter_expression": { + "test": "asyncio/api_reference/test_configuration.py::test_set_filter_expression", + "role": "open", + "mode": "live" + }, + "initialize_access_manager": { + "test": "asyncio/api_reference/test_configuration.py::test_initialize_access_manager", + "role": "open", + "mode": "live" + }, + "initialize_custom_event_loop": { + "test": "asyncio/api_reference/test_configuration.py::test_initialize_custom_event_loop", + "role": "open", + "mode": "live" + }, + "initialize_custom_request_handler": { + "test": "asyncio/api_reference/test_configuration.py::test_initialize_custom_request_handler", + "role": "open", + "mode": "live" + }, + "initialize_custom_user_id": { + "test": "asyncio/api_reference/test_configuration.py::test_initialize_pubnub", + "role": "open", + "mode": "live" + }, + "initialize_non_secure": { + "test": "asyncio/api_reference/test_configuration.py::test_initialize_pubnub", + "role": "open", + "mode": "live" + }, + "initialize_pubnub": { + "test": "asyncio/api_reference/test_configuration.py::test_initialize_pubnub", + "role": "open", + "mode": "live" + }, + "initialize_read_only": { + "test": "asyncio/api_reference/test_configuration.py::test_initialize_read_only", + "role": "open", + "mode": "live" + }, + "initialize_ssl": { + "test": "asyncio/api_reference/test_configuration.py::test_initialize_pubnub", + "role": "open", + "mode": "live" + }, + "set_filter_expression": { + "test": "asyncio/api_reference/test_configuration.py::test_set_filter_expression", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_file_sharing.py": { + "delete_file_builder": { + "test": "asyncio/api_reference/test_file_sharing.py::test_delete_file_builder", + "role": "open", + "mode": "live" + }, + "download_file_builder": { + "test": "asyncio/api_reference/test_file_sharing.py::test_download_file_builder", + "role": "open", + "mode": "live" + }, + "get_file_url_builder": { + "test": "asyncio/api_reference/test_file_sharing.py::test_get_file_url_builder", + "role": "open", + "mode": "live" + }, + "list_files_builder": { + "test": "asyncio/api_reference/test_file_sharing.py::test_list_files_builder", + "role": "open", + "mode": "live" + }, + "publish_file_message_builder": { + "test": "asyncio/api_reference/test_file_sharing.py::test_publish_file_message_builder", + "role": "open", + "mode": "live" + }, + "send_file_builder": { + "test": "asyncio/api_reference/test_file_sharing.py::test_send_file_builder", + "role": "open", + "mode": "live" + }, + "send_file_options": { + "test": "asyncio/api_reference/test_file_sharing.py::test_send_file_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_message_actions.py": { + "add_message_action_builder": { + "test": "asyncio/api_reference/test_message_actions.py::test_add_message_action_builder", + "role": "open", + "mode": "live" + }, + "add_message_action_named": { + "test": "asyncio/api_reference/test_message_actions.py::test_add_message_action_builder", + "role": "open", + "mode": "live" + }, + "get_message_actions_builder": { + "test": "asyncio/api_reference/test_message_actions.py::test_get_message_actions_builder", + "role": "open", + "mode": "live" + }, + "get_message_actions_named": { + "test": "asyncio/api_reference/test_message_actions.py::test_get_message_actions_builder", + "role": "open", + "mode": "live" + }, + "remove_message_action_builder": { + "test": "asyncio/api_reference/test_message_actions.py::test_remove_message_action_builder", + "role": "open", + "mode": "live" + }, + "remove_message_action_named": { + "test": "asyncio/api_reference/test_message_actions.py::test_remove_message_action_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_message_persistence.py": { + "delete_message_single_builder": { + "test": "asyncio/api_reference/test_message_persistence.py::test_delete_message_single_builder", + "role": "open", + "mode": "live" + }, + "delete_message_single_named": { + "test": "asyncio/api_reference/test_message_persistence.py::test_delete_message_single_builder", + "role": "open", + "mode": "live" + }, + "delete_messages_builder": { + "test": "asyncio/api_reference/test_message_persistence.py::test_delete_messages_builder", + "role": "open", + "mode": "live" + }, + "delete_messages_named": { + "test": "asyncio/api_reference/test_message_persistence.py::test_delete_messages_builder", + "role": "open", + "mode": "live" + }, + "fetch_history_builder": { + "test": "asyncio/api_reference/test_message_persistence.py::test_fetch_history_builder", + "role": "open", + "mode": "live" + }, + "fetch_history_multiple": { + "test": "asyncio/api_reference/test_message_persistence.py::test_fetch_history_multiple", + "role": "open", + "mode": "live" + }, + "fetch_history_named": { + "test": "asyncio/api_reference/test_message_persistence.py::test_fetch_history_builder", + "role": "open", + "mode": "live" + }, + "fetch_history_range": { + "test": "asyncio/api_reference/test_message_persistence.py::test_fetch_history_range", + "role": "open", + "mode": "live" + }, + "message_counts_builder": { + "test": "asyncio/api_reference/test_message_persistence.py::test_message_counts_builder", + "role": "open", + "mode": "live" + }, + "message_counts_multiple_builder": { + "test": "asyncio/api_reference/test_message_persistence.py::test_message_counts_builder", + "role": "open", + "mode": "live" + }, + "message_counts_multiple_named": { + "test": "asyncio/api_reference/test_message_persistence.py::test_message_counts_builder", + "role": "open", + "mode": "live" + }, + "message_counts_named": { + "test": "asyncio/api_reference/test_message_persistence.py::test_message_counts_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_message_persistence_legacy.py": { + "history_basic": { + "test": "asyncio/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + }, + "history_end": { + "test": "asyncio/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + }, + "history_include_timetoken": { + "test": "asyncio/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + }, + "history_paging": { + "test": "asyncio/api_reference/test_message_persistence_legacy.py::test_history_paging", + "role": "open", + "mode": "live" + }, + "history_reverse": { + "test": "asyncio/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + }, + "history_start_reverse": { + "test": "asyncio/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_misc.py": { + "get_subscribed_channel_groups": { + "test": "asyncio/api_reference/test_misc.py::test_get_subscribed_channels", + "role": "open", + "mode": "live" + }, + "get_subscribed_channels": { + "test": "asyncio/api_reference/test_misc.py::test_get_subscribed_channels", + "role": "open", + "mode": "live" + }, + "time_get": { + "test": "asyncio/api_reference/test_misc.py::test_time_get", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_mobile_push.py": { + "add_channels_to_push_builder": { + "test": "asyncio/api_reference/test_mobile_push.py::test_add_channels_to_push_builder", + "role": "open", + "mode": "live" + }, + "add_channels_to_push_kwargs": { + "test": "asyncio/api_reference/test_mobile_push.py::test_add_channels_to_push_builder", + "role": "open", + "mode": "live" + }, + "list_push_channels_builder": { + "test": "asyncio/api_reference/test_mobile_push.py::test_list_push_channels_builder", + "role": "open", + "mode": "live" + }, + "remove_channels_from_push_builder": { + "test": "asyncio/api_reference/test_mobile_push.py::test_remove_channels_from_push_builder", + "role": "open", + "mode": "live" + }, + "remove_device_from_push_builder": { + "test": "asyncio/api_reference/test_mobile_push.py::test_remove_device_from_push_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_objects.py": { + "get_all_channel_metadata_builder": { + "test": "asyncio/api_reference/test_objects.py::test_get_all_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_all_channel_metadata_named": { + "test": "asyncio/api_reference/test_objects.py::test_get_all_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_all_uuid_metadata_builder": { + "test": "asyncio/api_reference/test_objects.py::test_get_all_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_all_uuid_metadata_named": { + "test": "asyncio/api_reference/test_objects.py::test_get_all_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_channel_members_builder": { + "test": "asyncio/api_reference/test_objects.py::test_get_channel_members_builder", + "role": "open", + "mode": "live" + }, + "get_channel_members_named": { + "test": "asyncio/api_reference/test_objects.py::test_get_channel_members_builder", + "role": "open", + "mode": "live" + }, + "get_channel_metadata_builder": { + "test": "asyncio/api_reference/test_objects.py::test_get_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_channel_metadata_named": { + "test": "asyncio/api_reference/test_objects.py::test_get_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_memberships_builder": { + "test": "asyncio/api_reference/test_objects.py::test_get_memberships_builder", + "role": "open", + "mode": "live" + }, + "get_memberships_named": { + "test": "asyncio/api_reference/test_objects.py::test_get_memberships_builder", + "role": "open", + "mode": "live" + }, + "get_uuid_metadata_builder": { + "test": "asyncio/api_reference/test_objects.py::test_get_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_uuid_metadata_named": { + "test": "asyncio/api_reference/test_objects.py::test_get_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "manage_channel_members_builder": { + "test": "asyncio/api_reference/test_objects.py::test_manage_channel_members_builder", + "role": "open", + "mode": "live" + }, + "manage_channel_members_named": { + "test": "asyncio/api_reference/test_objects.py::test_manage_channel_members_builder", + "role": "open", + "mode": "live" + }, + "manage_memberships_builder": { + "test": "asyncio/api_reference/test_objects.py::test_manage_memberships_builder", + "role": "open", + "mode": "live" + }, + "manage_memberships_named": { + "test": "asyncio/api_reference/test_objects.py::test_manage_memberships_builder", + "role": "open", + "mode": "live" + }, + "pnchannelmembership_class": { + "test": "asyncio/api_reference/test_objects.py::test_pnchannelmembership_class", + "role": "open", + "mode": "live" + }, + "pnuuid_class": { + "test": "asyncio/api_reference/test_objects.py::test_pnuuid_class", + "role": "open", + "mode": "live" + }, + "remove_channel_members_builder": { + "test": "asyncio/api_reference/test_objects.py::test_remove_channel_members_builder", + "role": "open", + "mode": "live" + }, + "remove_channel_members_named": { + "test": "asyncio/api_reference/test_objects.py::test_remove_channel_members_builder", + "role": "open", + "mode": "live" + }, + "remove_channel_metadata_builder": { + "test": "asyncio/api_reference/test_objects.py::test_remove_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "remove_channel_metadata_named": { + "test": "asyncio/api_reference/test_objects.py::test_remove_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "remove_memberships_builder": { + "test": "asyncio/api_reference/test_objects.py::test_remove_memberships_builder", + "role": "open", + "mode": "live" + }, + "remove_memberships_named": { + "test": "asyncio/api_reference/test_objects.py::test_remove_memberships_builder", + "role": "open", + "mode": "live" + }, + "remove_uuid_metadata_builder": { + "test": "asyncio/api_reference/test_objects.py::test_remove_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "remove_uuid_metadata_named": { + "test": "asyncio/api_reference/test_objects.py::test_remove_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "set_channel_members_builder": { + "test": "asyncio/api_reference/test_objects.py::test_set_channel_members_builder", + "role": "open", + "mode": "live" + }, + "set_channel_members_named": { + "test": "asyncio/api_reference/test_objects.py::test_set_channel_members_builder", + "role": "open", + "mode": "live" + }, + "set_channel_metadata_builder": { + "test": "asyncio/api_reference/test_objects.py::test_set_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "set_channel_metadata_named": { + "test": "asyncio/api_reference/test_objects.py::test_set_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "set_memberships_builder": { + "test": "asyncio/api_reference/test_objects.py::test_set_memberships_builder", + "role": "open", + "mode": "live" + }, + "set_memberships_named": { + "test": "asyncio/api_reference/test_objects.py::test_set_memberships_builder", + "role": "open", + "mode": "live" + }, + "set_uuid_metadata_builder": { + "test": "asyncio/api_reference/test_objects.py::test_set_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "set_uuid_metadata_named": { + "test": "asyncio/api_reference/test_objects.py::test_set_uuid_metadata_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_presence.py": { + "get_state_builder": { + "test": "asyncio/api_reference/test_presence.py::test_set_state_builder", + "role": "open", + "mode": "live" + }, + "here_now_builder": { + "test": "asyncio/api_reference/test_presence.py::test_here_now_builder", + "role": "open", + "mode": "live" + }, + "here_now_groups": { + "test": "asyncio/api_reference/test_presence.py::test_here_now_groups", + "role": "open", + "mode": "live" + }, + "here_now_occupancy": { + "test": "asyncio/api_reference/test_presence.py::test_here_now_occupancy", + "role": "open", + "mode": "live" + }, + "here_now_state": { + "test": "asyncio/api_reference/test_presence.py::test_here_now_state", + "role": "open", + "mode": "live" + }, + "set_state_builder": { + "test": "asyncio/api_reference/test_presence.py::test_set_state_builder", + "role": "open", + "mode": "live" + }, + "set_state_groups_builder": { + "test": "asyncio/api_reference/test_presence.py::test_set_state_groups_builder", + "role": "open", + "mode": "live" + }, + "where_now_other": { + "test": "asyncio/api_reference/test_presence.py::test_where_now_self", + "role": "open", + "mode": "live" + }, + "where_now_self": { + "test": "asyncio/api_reference/test_presence.py::test_where_now_self", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_publish.py": { + "fire_message": { + "test": "asyncio/api_reference/test_publish.py::test_fire_message", + "role": "open", + "mode": "live" + }, + "fire_post": { + "test": "asyncio/api_reference/test_publish.py::test_fire_post", + "role": "open", + "mode": "live" + }, + "publish_builder": { + "test": "asyncio/api_reference/test_publish.py::test_publish_builder", + "role": "open", + "mode": "live" + }, + "publish_metadata": { + "test": "asyncio/api_reference/test_publish.py::test_publish_metadata", + "role": "open", + "mode": "live" + }, + "publish_named": { + "test": "asyncio/api_reference/test_publish.py::test_publish_builder", + "role": "open", + "mode": "live" + }, + "publish_store_post": { + "test": "asyncio/api_reference/test_publish.py::test_publish_store_post", + "role": "open", + "mode": "live" + }, + "signal_message": { + "test": "asyncio/api_reference/test_publish.py::test_signal_message", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_subscribe.py": { + "entity_channel": { + "test": "asyncio/api_reference/test_subscribe.py::test_entity_channel", + "role": "open", + "mode": "live" + }, + "entity_channel_group": { + "test": "asyncio/api_reference/test_subscribe.py::test_entity_channel", + "role": "open", + "mode": "live" + }, + "entity_channel_metadata": { + "test": "asyncio/api_reference/test_subscribe.py::test_entity_channel", + "role": "open", + "mode": "live" + }, + "entity_user_metadata": { + "test": "asyncio/api_reference/test_subscribe.py::test_entity_channel", + "role": "open", + "mode": "live" + }, + "listeners_event_specific": { + "test": "asyncio/api_reference/test_subscribe.py::test_listeners_event_specific", + "role": "open", + "mode": "live" + }, + "listeners_generic": { + "test": "asyncio/api_reference/test_subscribe.py::test_listeners_generic", + "role": "open", + "mode": "live" + }, + "listeners_presence": { + "test": "asyncio/api_reference/test_subscribe.py::test_listeners_presence", + "role": "open", + "mode": "live" + }, + "listeners_status": { + "test": "asyncio/api_reference/test_subscribe.py::test_listeners_status", + "role": "open", + "mode": "live" + }, + "listeners_subscription_set": { + "test": "asyncio/api_reference/test_subscribe.py::test_listeners_subscription_set", + "role": "open", + "mode": "live" + }, + "subscribe_multiple": { + "test": "asyncio/api_reference/test_subscribe.py::test_subscribe_multiple", + "role": "open", + "mode": "live" + }, + "subscribe_single": { + "test": "asyncio/api_reference/test_subscribe.py::test_subscribe_single", + "role": "open", + "mode": "live" + }, + "unsubscribe_all": { + "test": "asyncio/api_reference/test_subscribe.py::test_unsubscribe_all", + "role": "open", + "mode": "live" + }, + "unsubscribe_set": { + "test": "asyncio/api_reference/test_subscribe.py::test_unsubscribe_set", + "role": "open", + "mode": "live" + }, + "unsubscribe_subscription": { + "test": "asyncio/api_reference/test_subscribe.py::test_unsubscribe_subscription", + "role": "open", + "mode": "live" + } + }, + "tests/live/asyncio/api_reference/test_subscribe_legacy.py": { + "listeners_old_add": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_listeners_old_add", + "role": "open", + "mode": "live" + }, + "listeners_old_disconnects": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_listeners_old_disconnects", + "role": "open", + "mode": "live" + }, + "listeners_old_remove": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_listeners_old_remove", + "role": "open", + "mode": "live" + }, + "subscribe_old_channel": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_subscribe_old_channel", + "role": "open", + "mode": "live" + }, + "subscribe_old_group": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_subscribe_old_group", + "role": "open", + "mode": "live" + }, + "subscribe_old_group_presence": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_subscribe_old_presence", + "role": "open", + "mode": "live" + }, + "subscribe_old_logging": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_subscribe_old_logging", + "role": "open", + "mode": "live" + }, + "subscribe_old_multiple": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_subscribe_old_multiple", + "role": "open", + "mode": "live" + }, + "subscribe_old_presence": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_subscribe_old_presence", + "role": "open", + "mode": "live" + }, + "subscribe_old_state": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_subscribe_old_state", + "role": "open", + "mode": "live" + }, + "subscribe_old_wildcard": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_subscribe_old_wildcard", + "role": "open", + "mode": "live" + }, + "unsubscribe_all_old": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_unsubscribe_all_old", + "role": "open", + "mode": "live" + }, + "unsubscribe_old_channel": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_unsubscribe_old_channel", + "role": "open", + "mode": "live" + }, + "unsubscribe_old_group": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_unsubscribe_old_multiple", + "role": "open", + "mode": "live" + }, + "unsubscribe_old_multiple": { + "test": "asyncio/api_reference/test_subscribe_legacy.py::test_unsubscribe_old_multiple", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_access_manager.py": { + "grant_token_builder": { + "test": "sync/api_reference/test_access_manager.py::test_grant_token_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_categories": { + "test": "sync/api_reference/test_access_manager.py::test_grant_token_categories", + "role": "pam", + "mode": "live" + }, + "grant_token_multi": { + "test": "sync/api_reference/test_access_manager.py::test_grant_token_multi", + "role": "pam", + "mode": "live" + }, + "grant_token_multi_regex": { + "test": "sync/api_reference/test_access_manager.py::test_grant_token_multi", + "role": "pam", + "mode": "live" + }, + "grant_token_named": { + "test": "sync/api_reference/test_access_manager.py::test_grant_token_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_regex": { + "test": "sync/api_reference/test_access_manager.py::test_grant_token_multi", + "role": "pam", + "mode": "live" + }, + "parse_token": { + "test": "sync/api_reference/test_access_manager.py::test_grant_token_builder", + "role": "pam", + "mode": "live" + }, + "parse_token_categories": { + "test": "sync/api_reference/test_access_manager.py::test_grant_token_categories", + "role": "pam", + "mode": "live" + }, + "revoke_token": { + "test": "sync/api_reference/test_access_manager.py::test_revoke_token", + "role": "pam", + "mode": "live" + }, + "set_token": { + "test": "sync/api_reference/test_access_manager.py::test_set_token", + "role": "pam", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_access_manager_legacy.py": { + "grant_token_spaces_builder": { + "test": "sync/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_spaces_multi": { + "test": "sync/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_spaces_multi_regex": { + "test": "sync/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_spaces_named": { + "test": "sync/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + }, + "grant_token_spaces_regex": { + "test": "sync/api_reference/test_access_manager_legacy.py::test_grant_token_spaces_builder", + "role": "pam", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_access_manager_v2.py": { + "grant_application_level": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_subkey_all", + "role": "pam", + "mode": "live" + }, + "grant_categories": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_categories", + "role": "pam", + "mode": "live" + }, + "grant_channel_all_users": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_channel_all_users", + "role": "pam", + "mode": "live" + }, + "grant_channel_auth": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_channel_auth", + "role": "pam", + "mode": "live" + }, + "grant_channel_group": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_channel_group", + "role": "pam", + "mode": "live" + }, + "grant_channel_level": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_channel_all_users", + "role": "pam", + "mode": "live" + }, + "grant_channel_ro_auth": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_channel_ro_auth", + "role": "pam", + "mode": "live" + }, + "grant_multiple_channels": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_multiple_channels", + "role": "pam", + "mode": "live" + }, + "grant_presence": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_presence", + "role": "pam", + "mode": "live" + }, + "grant_subkey_all": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_subkey_all", + "role": "pam", + "mode": "live" + }, + "grant_user_level": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_channel_ro_auth", + "role": "pam", + "mode": "live" + }, + "grant_uuid": { + "test": "sync/api_reference/test_access_manager_v2.py::test_grant_uuid", + "role": "pam", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_channel_groups.py": { + "add_channels_builder": { + "test": "sync/api_reference/test_channel_groups.py::test_add_channels_builder", + "role": "open", + "mode": "live" + }, + "add_channels_named": { + "test": "sync/api_reference/test_channel_groups.py::test_add_channels_builder", + "role": "open", + "mode": "live" + }, + "delete_channel_group_builder": { + "test": "sync/api_reference/test_channel_groups.py::test_delete_channel_group_builder", + "role": "open", + "mode": "live" + }, + "list_channels_builder": { + "test": "sync/api_reference/test_channel_groups.py::test_list_channels_builder", + "role": "open", + "mode": "live" + }, + "list_channels_named": { + "test": "sync/api_reference/test_channel_groups.py::test_list_channels_builder", + "role": "open", + "mode": "live" + }, + "remove_channels_builder": { + "test": "sync/api_reference/test_channel_groups.py::test_remove_channels_builder", + "role": "open", + "mode": "live" + }, + "remove_channels_named": { + "test": "sync/api_reference/test_channel_groups.py::test_remove_channels_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_configuration.py": { + "configuration_full": { + "test": "sync/api_reference/test_configuration.py::test_configuration_full", + "role": "open", + "mode": "live" + }, + "get_filter_expression": { + "test": "sync/api_reference/test_configuration.py::test_set_filter_expression", + "role": "open", + "mode": "live" + }, + "initialize_access_manager": { + "test": "sync/api_reference/test_configuration.py::test_initialize_access_manager", + "role": "open", + "mode": "live" + }, + "initialize_custom_request_handler": { + "test": "sync/api_reference/test_configuration.py::test_initialize_custom_request_handler", + "role": "open", + "mode": "live" + }, + "initialize_custom_user_id": { + "test": "sync/api_reference/test_configuration.py::test_initialize_pubnub", + "role": "open", + "mode": "live" + }, + "initialize_non_secure": { + "test": "sync/api_reference/test_configuration.py::test_initialize_pubnub", + "role": "open", + "mode": "live" + }, + "initialize_pubnub": { + "test": "sync/api_reference/test_configuration.py::test_initialize_pubnub", + "role": "open", + "mode": "live" + }, + "initialize_read_only": { + "test": "sync/api_reference/test_configuration.py::test_initialize_read_only", + "role": "open", + "mode": "live" + }, + "initialize_ssl": { + "test": "sync/api_reference/test_configuration.py::test_initialize_pubnub", + "role": "open", + "mode": "live" + }, + "set_filter_expression": { + "test": "sync/api_reference/test_configuration.py::test_set_filter_expression", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_encryption.py": { + "cipher_mode_experiment": { + "test": "sync/api_reference/test_encryption.py::test_cipher_mode_experiment", + "mode": "live" + }, + "crypto_module_aes_cbc": { + "test": "sync/api_reference/test_encryption.py::test_crypto_module_aes_cbc", + "role": "open", + "mode": "live" + }, + "crypto_module_legacy": { + "test": "sync/api_reference/test_encryption.py::test_crypto_module_legacy", + "role": "open", + "mode": "live" + }, + "crypto_module_partial": { + "test": "sync/api_reference/test_encryption.py::test_crypto_module_partial", + "role": "open", + "mode": "live" + }, + "decrypt_file": { + "test": "sync/api_reference/test_encryption.py::test_encrypt_file", + "role": "open", + "mode": "live" + }, + "encrypt_file": { + "test": "sync/api_reference/test_encryption.py::test_encrypt_file", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_file_sharing.py": { + "delete_file_builder": { + "test": "sync/api_reference/test_file_sharing.py::test_delete_file_builder", + "role": "open", + "mode": "live" + }, + "delete_file_named": { + "test": "sync/api_reference/test_file_sharing.py::test_delete_file_builder", + "role": "open", + "mode": "live" + }, + "download_file_builder": { + "test": "sync/api_reference/test_file_sharing.py::test_download_file_builder", + "role": "open", + "mode": "live" + }, + "get_file_url_builder": { + "test": "sync/api_reference/test_file_sharing.py::test_get_file_url_builder", + "role": "open", + "mode": "live" + }, + "get_file_url_named": { + "test": "sync/api_reference/test_file_sharing.py::test_get_file_url_builder", + "role": "open", + "mode": "live" + }, + "list_files_builder": { + "test": "sync/api_reference/test_file_sharing.py::test_list_files_builder", + "role": "open", + "mode": "live" + }, + "list_files_named": { + "test": "sync/api_reference/test_file_sharing.py::test_list_files_builder", + "role": "open", + "mode": "live" + }, + "publish_file_message_builder": { + "test": "sync/api_reference/test_file_sharing.py::test_publish_file_message_builder", + "role": "open", + "mode": "live" + }, + "publish_file_message_callback": { + "test": "sync/api_reference/test_file_sharing.py::test_publish_file_message_builder", + "role": "open", + "mode": "live" + }, + "send_file_builder": { + "test": "sync/api_reference/test_file_sharing.py::test_send_file_builder", + "role": "open", + "mode": "live" + }, + "send_file_custom_message_type": { + "test": "sync/api_reference/test_file_sharing.py::test_send_file_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_message_actions.py": { + "add_message_action_builder": { + "test": "sync/api_reference/test_message_actions.py::test_add_message_action_builder", + "role": "open", + "mode": "live" + }, + "add_message_action_named": { + "test": "sync/api_reference/test_message_actions.py::test_add_message_action_builder", + "role": "open", + "mode": "live" + }, + "get_message_actions_builder": { + "test": "sync/api_reference/test_message_actions.py::test_get_message_actions_builder", + "role": "open", + "mode": "live" + }, + "get_message_actions_named": { + "test": "sync/api_reference/test_message_actions.py::test_get_message_actions_builder", + "role": "open", + "mode": "live" + }, + "remove_message_action_builder": { + "test": "sync/api_reference/test_message_actions.py::test_remove_message_action_builder", + "role": "open", + "mode": "live" + }, + "remove_message_action_named": { + "test": "sync/api_reference/test_message_actions.py::test_remove_message_action_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_message_persistence.py": { + "delete_message_single_builder": { + "test": "sync/api_reference/test_message_persistence.py::test_delete_message_single_builder", + "role": "open", + "mode": "live" + }, + "delete_message_single_named": { + "test": "sync/api_reference/test_message_persistence.py::test_delete_message_single_builder", + "role": "open", + "mode": "live" + }, + "delete_messages_builder": { + "test": "sync/api_reference/test_message_persistence.py::test_delete_messages_builder", + "role": "open", + "mode": "live" + }, + "delete_messages_named": { + "test": "sync/api_reference/test_message_persistence.py::test_delete_messages_builder", + "role": "open", + "mode": "live" + }, + "fetch_history_builder": { + "test": "sync/api_reference/test_message_persistence.py::test_fetch_history_builder", + "role": "open", + "mode": "live" + }, + "fetch_history_multiple": { + "test": "sync/api_reference/test_message_persistence.py::test_fetch_history_multiple", + "role": "open", + "mode": "live" + }, + "fetch_history_named": { + "test": "sync/api_reference/test_message_persistence.py::test_fetch_history_builder", + "role": "open", + "mode": "live" + }, + "fetch_history_range": { + "test": "sync/api_reference/test_message_persistence.py::test_fetch_history_range", + "role": "open", + "mode": "live" + }, + "message_counts_builder": { + "test": "sync/api_reference/test_message_persistence.py::test_message_counts_builder", + "role": "open", + "mode": "live" + }, + "message_counts_multiple_builder": { + "test": "sync/api_reference/test_message_persistence.py::test_message_counts_builder", + "role": "open", + "mode": "live" + }, + "message_counts_multiple_named": { + "test": "sync/api_reference/test_message_persistence.py::test_message_counts_builder", + "role": "open", + "mode": "live" + }, + "message_counts_named": { + "test": "sync/api_reference/test_message_persistence.py::test_message_counts_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_message_persistence_legacy.py": { + "history_basic": { + "test": "sync/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + }, + "history_end": { + "test": "sync/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + }, + "history_include_timetoken": { + "test": "sync/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + }, + "history_paging": { + "test": "sync/api_reference/test_message_persistence_legacy.py::test_history_paging", + "role": "open", + "mode": "live" + }, + "history_reverse": { + "test": "sync/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + }, + "history_start_reverse": { + "test": "sync/api_reference/test_message_persistence_legacy.py::test_history_basic", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_misc.py": { + "disconnect_method": { + "test": "sync/api_reference/test_misc.py::test_disconnect_method", + "role": "open", + "mode": "live" + }, + "get_subscribed_channel_groups": { + "test": "sync/api_reference/test_misc.py::test_get_subscribed_channels", + "role": "open", + "mode": "live" + }, + "get_subscribed_channels": { + "test": "sync/api_reference/test_misc.py::test_get_subscribed_channels", + "role": "open", + "mode": "live" + }, + "reconnect_documented": { + "test": "sync/api_reference/test_misc.py::test_reconnect_documented", + "role": "open", + "mode": "live" + }, + "reconnect_method": { + "test": "sync/api_reference/test_misc.py::test_disconnect_method", + "role": "open", + "mode": "live" + }, + "time_get": { + "test": "sync/api_reference/test_misc.py::test_time_get", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_mobile_push.py": { + "add_channels_to_push_builder": { + "test": "sync/api_reference/test_mobile_push.py::test_add_channels_to_push_builder", + "role": "open", + "mode": "live" + }, + "add_channels_to_push_named": { + "test": "sync/api_reference/test_mobile_push.py::test_add_channels_to_push_builder", + "role": "open", + "mode": "live" + }, + "list_push_channels_builder": { + "test": "sync/api_reference/test_mobile_push.py::test_list_push_channels_builder", + "role": "open", + "mode": "live" + }, + "list_push_channels_named": { + "test": "sync/api_reference/test_mobile_push.py::test_list_push_channels_builder", + "role": "open", + "mode": "live" + }, + "remove_channels_from_push_builder": { + "test": "sync/api_reference/test_mobile_push.py::test_remove_channels_from_push_builder", + "role": "open", + "mode": "live" + }, + "remove_channels_from_push_named": { + "test": "sync/api_reference/test_mobile_push.py::test_remove_channels_from_push_builder", + "role": "open", + "mode": "live" + }, + "remove_device_from_push_builder": { + "test": "sync/api_reference/test_mobile_push.py::test_remove_device_from_push_builder", + "role": "open", + "mode": "live" + }, + "remove_device_from_push_named": { + "test": "sync/api_reference/test_mobile_push.py::test_remove_device_from_push_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_objects.py": { + "get_all_channel_metadata_builder": { + "test": "sync/api_reference/test_objects.py::test_get_all_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_all_channel_metadata_named": { + "test": "sync/api_reference/test_objects.py::test_get_all_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_all_uuid_metadata_builder": { + "test": "sync/api_reference/test_objects.py::test_get_all_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_all_uuid_metadata_named": { + "test": "sync/api_reference/test_objects.py::test_get_all_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_channel_members_builder": { + "test": "sync/api_reference/test_objects.py::test_get_channel_members_builder", + "role": "open", + "mode": "live" + }, + "get_channel_members_named": { + "test": "sync/api_reference/test_objects.py::test_get_channel_members_builder", + "role": "open", + "mode": "live" + }, + "get_channel_metadata_builder": { + "test": "sync/api_reference/test_objects.py::test_get_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_channel_metadata_named": { + "test": "sync/api_reference/test_objects.py::test_get_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_memberships_builder": { + "test": "sync/api_reference/test_objects.py::test_get_memberships_builder", + "role": "open", + "mode": "live" + }, + "get_memberships_named": { + "test": "sync/api_reference/test_objects.py::test_get_memberships_builder", + "role": "open", + "mode": "live" + }, + "get_uuid_metadata_builder": { + "test": "sync/api_reference/test_objects.py::test_get_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "get_uuid_metadata_named": { + "test": "sync/api_reference/test_objects.py::test_get_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "manage_channel_members_builder": { + "test": "sync/api_reference/test_objects.py::test_manage_channel_members_builder", + "role": "open", + "mode": "live" + }, + "manage_channel_members_named": { + "test": "sync/api_reference/test_objects.py::test_manage_channel_members_builder", + "role": "open", + "mode": "live" + }, + "manage_memberships_builder": { + "test": "sync/api_reference/test_objects.py::test_manage_memberships_builder", + "role": "open", + "mode": "live" + }, + "manage_memberships_named": { + "test": "sync/api_reference/test_objects.py::test_manage_memberships_builder", + "role": "open", + "mode": "live" + }, + "pnchannelmembership_class": { + "test": "sync/api_reference/test_objects.py::test_pnchannelmembership_class", + "role": "open", + "mode": "live" + }, + "pnuuid_class": { + "test": "sync/api_reference/test_objects.py::test_pnuuid_class", + "role": "open", + "mode": "live" + }, + "remove_channel_members_builder": { + "test": "sync/api_reference/test_objects.py::test_remove_channel_members_builder", + "role": "open", + "mode": "live" + }, + "remove_channel_members_named": { + "test": "sync/api_reference/test_objects.py::test_remove_channel_members_builder", + "role": "open", + "mode": "live" + }, + "remove_channel_metadata_builder": { + "test": "sync/api_reference/test_objects.py::test_remove_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "remove_channel_metadata_named": { + "test": "sync/api_reference/test_objects.py::test_remove_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "remove_memberships_builder": { + "test": "sync/api_reference/test_objects.py::test_remove_memberships_builder", + "role": "open", + "mode": "live" + }, + "remove_memberships_named": { + "test": "sync/api_reference/test_objects.py::test_remove_memberships_builder", + "role": "open", + "mode": "live" + }, + "remove_uuid_metadata_builder": { + "test": "sync/api_reference/test_objects.py::test_remove_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "remove_uuid_metadata_named": { + "test": "sync/api_reference/test_objects.py::test_remove_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "set_channel_members_builder": { + "test": "sync/api_reference/test_objects.py::test_set_channel_members_builder", + "role": "open", + "mode": "live" + }, + "set_channel_members_named": { + "test": "sync/api_reference/test_objects.py::test_set_channel_members_builder", + "role": "open", + "mode": "live" + }, + "set_channel_metadata_builder": { + "test": "sync/api_reference/test_objects.py::test_set_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "set_channel_metadata_named": { + "test": "sync/api_reference/test_objects.py::test_set_channel_metadata_builder", + "role": "open", + "mode": "live" + }, + "set_memberships_builder": { + "test": "sync/api_reference/test_objects.py::test_set_memberships_builder", + "role": "open", + "mode": "live" + }, + "set_memberships_named": { + "test": "sync/api_reference/test_objects.py::test_set_memberships_builder", + "role": "open", + "mode": "live" + }, + "set_uuid_metadata_builder": { + "test": "sync/api_reference/test_objects.py::test_set_uuid_metadata_builder", + "role": "open", + "mode": "live" + }, + "set_uuid_metadata_named": { + "test": "sync/api_reference/test_objects.py::test_set_uuid_metadata_builder", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_presence.py": { + "get_state_builder": { + "test": "sync/api_reference/test_presence.py::test_set_state_builder", + "role": "open", + "mode": "live" + }, + "get_state_named": { + "test": "sync/api_reference/test_presence.py::test_set_state_builder", + "role": "open", + "mode": "live" + }, + "here_now_builder": { + "test": "sync/api_reference/test_presence.py::test_here_now_builder", + "role": "open", + "mode": "live" + }, + "here_now_groups": { + "test": "sync/api_reference/test_presence.py::test_here_now_groups", + "role": "open", + "mode": "live" + }, + "here_now_named": { + "test": "sync/api_reference/test_presence.py::test_here_now_builder", + "role": "open", + "mode": "live" + }, + "here_now_occupancy": { + "test": "sync/api_reference/test_presence.py::test_here_now_occupancy", + "role": "open", + "mode": "live" + }, + "here_now_paginate": { + "test": "sync/api_reference/test_presence.py::test_here_now_paginate", + "role": "open", + "mode": "live" + }, + "here_now_state": { + "test": "sync/api_reference/test_presence.py::test_here_now_state", + "role": "open", + "mode": "live" + }, + "set_state_builder": { + "test": "sync/api_reference/test_presence.py::test_set_state_builder", + "role": "open", + "mode": "live" + }, + "set_state_groups_builder": { + "test": "sync/api_reference/test_presence.py::test_set_state_groups_builder", + "role": "open", + "mode": "live" + }, + "set_state_groups_named": { + "test": "sync/api_reference/test_presence.py::test_set_state_groups_builder", + "role": "open", + "mode": "live" + }, + "set_state_named": { + "test": "sync/api_reference/test_presence.py::test_set_state_builder", + "role": "open", + "mode": "live" + }, + "where_now_other_builder": { + "test": "sync/api_reference/test_presence.py::test_where_now_self", + "role": "open", + "mode": "live" + }, + "where_now_other_named": { + "test": "sync/api_reference/test_presence.py::test_where_now_self", + "role": "open", + "mode": "live" + }, + "where_now_self": { + "test": "sync/api_reference/test_presence.py::test_where_now_self", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_publish.py": { + "fire_message": { + "test": "sync/api_reference/test_publish.py::test_fire_message", + "role": "open", + "mode": "live" + }, + "fire_named": { + "test": "sync/api_reference/test_publish.py::test_fire_post", + "role": "open", + "mode": "live" + }, + "fire_post": { + "test": "sync/api_reference/test_publish.py::test_fire_post", + "role": "open", + "mode": "live" + }, + "publish_builder": { + "test": "sync/api_reference/test_publish.py::test_publish_builder", + "role": "open", + "mode": "live" + }, + "publish_metadata": { + "test": "sync/api_reference/test_publish.py::test_publish_metadata", + "role": "open", + "mode": "live" + }, + "publish_named": { + "test": "sync/api_reference/test_publish.py::test_publish_builder", + "role": "open", + "mode": "live" + }, + "publish_store_post": { + "test": "sync/api_reference/test_publish.py::test_publish_store_post", + "role": "open", + "mode": "live" + }, + "signal_message": { + "test": "sync/api_reference/test_publish.py::test_signal_message", + "role": "open", + "mode": "live" + }, + "signal_named": { + "test": "sync/api_reference/test_publish.py::test_signal_named", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_subscribe.py": { + "entity_channel": { + "test": "sync/api_reference/test_subscribe.py::test_entity_channel", + "role": "open", + "mode": "live" + }, + "entity_channel_group": { + "test": "sync/api_reference/test_subscribe.py::test_entity_channel", + "role": "open", + "mode": "live" + }, + "entity_channel_metadata": { + "test": "sync/api_reference/test_subscribe.py::test_entity_channel", + "role": "open", + "mode": "live" + }, + "entity_user_metadata": { + "test": "sync/api_reference/test_subscribe.py::test_entity_channel", + "role": "open", + "mode": "live" + }, + "listeners_event_specific": { + "test": "sync/api_reference/test_subscribe.py::test_listeners_event_specific", + "role": "open", + "mode": "live" + }, + "listeners_generic": { + "test": "sync/api_reference/test_subscribe.py::test_listeners_generic", + "role": "open", + "mode": "live" + }, + "listeners_presence": { + "test": "sync/api_reference/test_subscribe.py::test_listeners_presence", + "role": "open", + "mode": "live" + }, + "listeners_status": { + "test": "sync/api_reference/test_subscribe.py::test_listeners_status", + "role": "open", + "mode": "live" + }, + "listeners_subscription_set": { + "test": "sync/api_reference/test_subscribe.py::test_listeners_subscription_set", + "role": "open", + "mode": "live" + }, + "subscribe_multiple": { + "test": "sync/api_reference/test_subscribe.py::test_subscribe_multiple", + "role": "open", + "mode": "live" + }, + "subscribe_single": { + "test": "sync/api_reference/test_subscribe.py::test_subscribe_single", + "role": "open", + "mode": "live" + }, + "unsubscribe_all": { + "test": "sync/api_reference/test_subscribe.py::test_unsubscribe_all", + "role": "open", + "mode": "live" + }, + "unsubscribe_set": { + "test": "sync/api_reference/test_subscribe.py::test_unsubscribe_set", + "role": "open", + "mode": "live" + }, + "unsubscribe_subscription": { + "test": "sync/api_reference/test_subscribe.py::test_unsubscribe_subscription", + "role": "open", + "mode": "live" + } + }, + "tests/live/sync/api_reference/test_subscribe_legacy.py": { + "listeners_old_add": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_listeners_old_add", + "role": "open", + "mode": "live" + }, + "listeners_old_disconnects": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_listeners_old_disconnects", + "role": "open", + "mode": "live" + }, + "listeners_old_remove": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_listeners_old_remove", + "role": "open", + "mode": "live" + }, + "subscribe_old_channel": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_subscribe_old_channel", + "role": "open", + "mode": "live" + }, + "subscribe_old_group": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_subscribe_old_group", + "role": "open", + "mode": "live" + }, + "subscribe_old_group_presence": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_subscribe_old_presence", + "role": "open", + "mode": "live" + }, + "subscribe_old_logging": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_subscribe_old_logging", + "role": "open", + "mode": "live" + }, + "subscribe_old_multiple": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_subscribe_old_multiple", + "role": "open", + "mode": "live" + }, + "subscribe_old_presence": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_subscribe_old_presence", + "role": "open", + "mode": "live" + }, + "subscribe_old_state": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_subscribe_old_state", + "role": "open", + "mode": "live" + }, + "subscribe_old_wildcard": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_subscribe_old_wildcard", + "role": "open", + "mode": "live" + }, + "unsubscribe_all_old": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_unsubscribe_all_old", + "role": "open", + "mode": "live" + }, + "unsubscribe_old_channel": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_unsubscribe_old_channel", + "role": "open", + "mode": "live" + }, + "unsubscribe_old_group": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_unsubscribe_old_multiple", + "role": "open", + "mode": "live" + }, + "unsubscribe_old_multiple": { + "test": "sync/api_reference/test_subscribe_legacy.py::test_unsubscribe_old_multiple", + "role": "open", + "mode": "live" + } + } + }, + "whole_files": {} +} diff --git a/tests/live/fixtures/sample.gif b/tests/live/fixtures/sample.gif new file mode 100644 index 00000000..a5fd168e Binary files /dev/null and b/tests/live/fixtures/sample.gif differ diff --git a/tests/live/groups.py b/tests/live/groups.py new file mode 100644 index 00000000..01a55c58 --- /dev/null +++ b/tests/live/groups.py @@ -0,0 +1,90 @@ +"""API groups of the live tier. DATA ONLY. One group is one job of the "Live tests" workflow +(.github/workflows/live-integration.yml) and one `LIVE_GROUP=` run: + + cd tests/live && LIVE_GROUP=messaging python -u -m pytest + +`roles`: a group run without -k needs exactly these keyset roles up front, and the preflight and the wait for a closed +Access Manager grant cover only these roles. The workflow builds its job matrix from this list +(python -u tests/live/cli.py groups --matrix). + +Every test file of the tier belongs to exactly one group. An entry is a file path relative to tests/live/, or a +"::" node id that takes one test out of the group that lists its file. `cli.py groups --check` (run by +`cli.py lint`) fails on a test file in no group or in two groups, a listed file or test that does not exist, a role a +file uses that its group does not list, and a workflow `group` input whose options differ from these names. + +Order is the order of the serial run in CI. access-manager-application-level runs last: its tests open the whole +pam keyset for a moment. +""" + +GROUPS = [ + { + 'name': 'messaging', + 'tier': 'docs', + 'roles': ['open'], + 'files': [ + 'sync/api_reference/test_publish.py', + 'asyncio/api_reference/test_publish.py', + 'sync/api_reference/test_subscribe.py', + 'asyncio/api_reference/test_subscribe.py', + 'sync/api_reference/test_subscribe_legacy.py', + 'asyncio/api_reference/test_subscribe_legacy.py', + 'sync/api_reference/test_presence.py', + 'asyncio/api_reference/test_presence.py', + 'sync/api_reference/test_channel_groups.py', + 'asyncio/api_reference/test_channel_groups.py', + 'sync/api_reference/test_message_persistence.py', + 'asyncio/api_reference/test_message_persistence.py', + 'sync/api_reference/test_message_persistence_legacy.py', + 'asyncio/api_reference/test_message_persistence_legacy.py', + 'sync/api_reference/test_message_actions.py', + 'asyncio/api_reference/test_message_actions.py', + 'sync/api_reference/test_file_sharing.py', + 'asyncio/api_reference/test_file_sharing.py', + 'sync/api_reference/test_mobile_push.py', + 'asyncio/api_reference/test_mobile_push.py', + ], + }, + { + 'name': 'getting-started', + 'tier': 'docs', + 'roles': ['open', 'pam'], + 'files': [ + 'sync/api_reference/test_configuration.py', + 'asyncio/api_reference/test_configuration.py', + 'sync/api_reference/test_encryption.py', + 'sync/api_reference/test_misc.py', + 'asyncio/api_reference/test_misc.py', + ], + }, + { + 'name': 'app-context', + 'tier': 'docs', + 'roles': ['open'], + 'files': [ + 'sync/api_reference/test_objects.py', + 'asyncio/api_reference/test_objects.py', + ], + }, + { + 'name': 'access-manager', + 'tier': 'docs', + 'roles': ['open', 'pam'], + 'files': [ + 'sync/api_reference/test_access_manager.py', + 'asyncio/api_reference/test_access_manager.py', + 'sync/api_reference/test_access_manager_legacy.py', + 'asyncio/api_reference/test_access_manager_legacy.py', + 'sync/api_reference/test_access_manager_v2.py', + 'asyncio/api_reference/test_access_manager_v2.py', + ], + }, + { + 'name': 'access-manager-application-level', + 'tier': 'docs', + 'roles': ['pam'], + 'files': [ + 'sync/api_reference/test_access_manager_v2.py::test_grant_subkey_all', + 'asyncio/api_reference/test_access_manager_v2.py::test_grant_subkey_all', + ], + }, +] diff --git a/tests/live/pytest.ini b/tests/live/pytest.ini new file mode 100644 index 00000000..792fb1fc --- /dev/null +++ b/tests/live/pytest.ini @@ -0,0 +1,19 @@ +[pytest] +# Own config of the live tier (README.md). The root run (py.test tests) never collects this folder: tests/conftest.py +# has collect_ignore = ["live"] and scripts/run-tests.py passes --ignore=tests/live/. +# python -u -m pytest -c tests/live/pytest.ini +python_files = test_*.py +python_functions = test_* +testpaths = sync asyncio +pythonpath = . +addopts = --import-mode=importlib -p no:cacheprovider -p no:randomly --strict-markers +asyncio_mode = auto +asyncio_default_fixture_loop_scope = function +log_level = INFO +# Per-test timeout (pytest-timeout), 120 s for every test by default. Tests that need more carry +# @pytest.mark.timeout(n). +timeout = 120 +filterwarnings = + ignore:Mutable config will be deprecated in the future.:DeprecationWarning + ignore:Access management v2 is being deprecated.:DeprecationWarning + ignore:.*Usage of local cipher_keys is discouraged.*:UserWarning diff --git a/tests/live/shared/__init__.py b/tests/live/shared/__init__.py new file mode 100644 index 00000000..7b15d69e --- /dev/null +++ b/tests/live/shared/__init__.py @@ -0,0 +1 @@ +"""Shared scenario data per docs page for the sync and asyncio docsets: resource names and helpers both call.""" diff --git a/tests/live/shared/access_manager.py b/tests/live/shared/access_manager.py new file mode 100644 index 00000000..fd6edb6a --- /dev/null +++ b/tests/live/shared/access_manager.py @@ -0,0 +1,70 @@ +"""Scenario data and helpers of the access-manager page, shared by the sync and asyncio tests: literal resource names +(NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from pubnub.exceptions import PubNubException +from pubnub.exceptions import PubNubAsyncioException + +from support import assertions as a + +NAMES = ['my-authorized-uuid', 'readonly-channel', 'readwrite-channel', 'revoke-channel', 'set_token_other_channel'] + + +FLAGS = ('read', 'write', 'manage', 'delete', 'get', 'update', 'join') + + +def perms(*on): + """The seven flags parse_token returns for one resource, True only for the ones named.""" + return {flag: flag in on for flag in FLAGS} + + +def holder(clients, user_id, token=None): + """A client that holds a token. It has no secret key, so every request is checked against the token.""" + client = clients.sync('pam', user_id, secret=False) + if token: + client.set_token(token) + return client + + +def publish(client, channel): + return client.publish().channel(channel).message('docs').sync() + + +def refused(client, channel): + """A publish the service answers with 403.""" + error = a.raises(PubNubException, publish, client, channel) + a.eq(error.get_status_code(), 403, 'status code of the refusal') + + +def allowed(client, channel): + a.timetoken(publish(client, channel).result.timetoken) + + +def holder_async(aclients, user_id, token=None): + """A client that holds a token. It has no secret key, so every request is checked against the token.""" + client = aclients.asyncio('pam', user_id, secret=False) + if token: + client.set_token(token) + return client + + +async def publish_async(client, channel): + return await client.publish().channel(channel).message('docs').future() + + +async def refused_async(client, channel): + resolved = await publish_async(client, channel) + a.ok(isinstance(resolved, PubNubAsyncioException), 'the publish was refused') + a.eq(resolved.status.status_code, 403, 'status code of the refusal') + + +async def allowed_async(client, channel): + resolved = await publish_async(client, channel) + a.ok(not isinstance(resolved, PubNubAsyncioException), 'the publish went through') + a.timetoken(resolved.result.timetoken) + + +def failure(resolved): + """The error text of a future() that resolved with an error.""" + a.ok(isinstance(resolved, PubNubAsyncioException), 'the call resolved with an error object') + return str(resolved.value()) diff --git a/tests/live/shared/access_manager_v2.py b/tests/live/shared/access_manager_v2.py new file mode 100644 index 00000000..f8ff26f3 --- /dev/null +++ b/tests/live/shared/access_manager_v2.py @@ -0,0 +1,125 @@ +"""Scenario data and helpers of the access-manager-v2 page, shared by the sync and asyncio tests: literal resource names +(NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from pubnub.exceptions import PubNubException +from pubnub.exceptions import PubNubAsyncioException + +from support import assertions as a + +NAMES = ['cg2', 'cg3', 'ch_no_grant', 'girish', 'girish2', 'group_member', 'my_channel-pnpres'] + + +ALL_FALSE = ('read', 'write', 'manage', 'delete', 'get', 'update', 'join') + + +def holder(clients, user_id, auth_key=None): + """A client that has no secret key, so every request is checked against its auth key.""" + client = clients.sync('pam', user_id, secret=False) + client.config.auth_key = auth_key + return client + + +def close_grant(admin, channels=None, groups=None, uuids=None, auth_keys=None): + """Take back what a step granted: every flag false, ttl 1.""" + builder = admin.grant() + for flag in ALL_FALSE: + builder = getattr(builder, flag)(False) + if channels: + builder = builder.channels(channels) + if groups: + builder = builder.channel_groups(groups) + if uuids: + builder = builder.uuids(uuids) + if auth_keys: + builder = builder.auth_keys(auth_keys) + return builder.ttl(1).sync() + + +def publish(client, channel): + return client.publish().channel(channel).message('docs').sync() + + +def refused(client, channel): + error = a.raises(PubNubException, publish, client, channel) + a.eq(error.get_status_code(), 403, 'status code of the refusal') + + +def allowed(client, channel): + a.timetoken(publish(client, channel).result.timetoken) + + +def key_flags(key_data): + return (key_data.read_enabled, key_data.write_enabled, key_data.manage_enabled, key_data.delete_enabled) + + +FLAGS = ('read', 'write', 'manage', 'delete', 'get', 'update', 'join') + + +def close_application_level(admin): + builder = admin.grant() + for flag in FLAGS: + builder = getattr(builder, flag)(False) + return builder.ttl(1).sync() + + +def holder_async(aclients, user_id, auth_key=None): + """A client that has no secret key, so every request is checked against its auth key.""" + client = aclients.asyncio('pam', user_id, secret=False) + client.config.auth_key = auth_key + return client + + +async def close_grant_async(admin, channels=None, groups=None, uuids=None, auth_keys=None): + """Take back what a step granted: every flag false, ttl 1.""" + builder = admin.grant() + for flag in ALL_FALSE: + builder = getattr(builder, flag)(False) + if channels: + builder = builder.channels(channels) + if groups: + builder = builder.channel_groups(groups) + if uuids: + builder = builder.uuids(uuids) + if auth_keys: + builder = builder.auth_keys(auth_keys) + return await builder.ttl(1).future() + + +async def publish_async(client, channel): + return await client.publish().channel(channel).message('docs').future() + + +async def refused_async(client, channel): + resolved = await publish_async(client, channel) + a.ok(isinstance(resolved, PubNubAsyncioException), 'the publish was refused') + a.eq(resolved.status.status_code, 403, 'status code of the refusal') + + +async def allowed_async(client, channel): + resolved = await publish_async(client, channel) + a.ok(not isinstance(resolved, PubNubAsyncioException), 'the publish went through') + a.timetoken(resolved.result.timetoken) + + +def good(resolved): + """A future() that resolved with a result, not with an error object. Returns the result.""" + a.ok(not isinstance(resolved, PubNubAsyncioException), 'the call succeeded') + return resolved.result + + +def failure(resolved): + a.ok(isinstance(resolved, PubNubAsyncioException), 'the call resolved with an error object') + return str(resolved.value()) + + +async def close_application_level_async(admin): + builder = admin.grant() + for flag in FLAGS: + builder = getattr(builder, flag)(False) + return await builder.ttl(1).future() + + +def accepted(resolved): + a.ok(not isinstance(resolved, PubNubAsyncioException), 'the grant was accepted') + return resolved.result diff --git a/tests/live/shared/channel_groups.py b/tests/live/shared/channel_groups.py new file mode 100644 index 00000000..e486e42e --- /dev/null +++ b/tests/live/shared/channel_groups.py @@ -0,0 +1,31 @@ +"""Scenario data and helpers of the channel-groups page, shared by the sync and asyncio tests: literal resource names +(NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from support import assertions as a +from support.wait import asettled, settled + +NAMES = ['channel_group', 'daughter', 'missing_group', 'son'] + + +def members(client, group): + return sorted(client.list_channels_in_channel_group().channel_group(group).sync().result.channels) + + +def eventually_members(client, group, expected): + """The group lists exactly `expected` on consecutive reads. A precondition that passes once can still be stale + on the next read (the sample's), and a later exact read must not see the state before a write.""" + settled(lambda: a.eq(members(client, group), sorted(expected), 'channels in the group'), timeout=30, + what='group membership') + + +async def members_async(client, group): + envelope = await client.list_channels_in_channel_group().channel_group(group).future() + return sorted(envelope.result.channels) + + +async def eventually_members_async(client, group, expected): + async def check(): + a.eq(await members_async(client, group), sorted(expected), 'channels in the group') + + await asettled(check, timeout=30, what='group membership') diff --git a/tests/live/shared/configuration.py b/tests/live/shared/configuration.py new file mode 100644 index 00000000..eafaf162 --- /dev/null +++ b/tests/live/shared/configuration.py @@ -0,0 +1,63 @@ +"""Scenario data and helpers of the configuration page, shared by the sync and asyncio tests: literal resource names +(NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from support import assertions as a +from support.clients import config as client_config + +NAMES = ['configured_user', 'filtered'] + + +USER_ID_ERROR = 'UUID missing or invalid type' # pubnub/pnconfiguration.py, validate_not_empty_string + + +UNREACHABLE = '127.0.0.1:1' + + +def real_keys(config): + """Copy the keyset of the open role onto a config the sample built with made up keys.""" + real = client_config('open') + config.subscribe_key = real.subscribe_key + config.publish_key = real.publish_key + + +def works(clients, pubnub, config): + """Overwrite the made up keys and prove the client talks to the service. Returns the time() envelope.""" + clients._made.append(pubnub) + real_keys(config) + config.daemon = True + envelope = pubnub.time().sync() + a.timetoken(str(envelope.result)) + return envelope + + +class RequestCounter: + """Replaces the request handler call so that a validation branch can prove no request was sent.""" + + def __init__(self): + self.calls = 0 + + def __call__(self, *args, **kwargs): + self.calls += 1 + raise RuntimeError('a request was sent') + + +async def works_async(aclients, pubnub, config): + """Overwrite the made up keys and prove the client talks to the service. Returns the time() envelope.""" + aclients._made.append(pubnub) + real_keys(config) + envelope = await pubnub.time().future() + a.ok(not envelope.status.is_error(), 'time() succeeded') + a.timetoken(str(envelope.result)) + return envelope + + +class RequestCounter_async: + """Replaces the network call of the request handler so that a validation branch can prove nothing was sent.""" + + def __init__(self): + self.calls = 0 + + async def __call__(self, *args, **kwargs): + self.calls += 1 + raise RuntimeError('a request was sent') diff --git a/tests/live/shared/encryption.py b/tests/live/shared/encryption.py new file mode 100644 index 00000000..c9f67015 --- /dev/null +++ b/tests/live/shared/encryption.py @@ -0,0 +1,42 @@ +"""Scenario data and helpers of the encryption page, shared by the sync and asyncio tests: literal resource names +(NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from pathlib import Path + +from Cryptodome.Cipher import AES +from pubnub.pubnub import PubNub + +from support import assertions as a +from support.clients import config as client_config +from support.wait import eventually + +NAMES = ['cipher_algorithm_experiment'] + + +FIXTURE_BYTES = (Path(__file__).resolve().parent.parent / 'fixtures' / 'sample.gif').read_bytes() + + +CBC_HEADER_B64 = 'UE5FRA' # base64 of the "PNED" sentinel that starts every 256-bit AES-CBC payload + + +def reader(clients, user, module=None, key='my_cipher_key'): + """A client that reads with the given crypto module, or with none.""" + config = client_config('open', user) + config.cipher_key = key + config.cipher_mode = AES.MODE_GCM + config.fallback_cipher_mode = AES.MODE_CBC + if module is None: + config.cipher_key = None + config.cipher_mode = AES.MODE_CBC + config.fallback_cipher_mode = None + else: + config.crypto_module = module(config) + client = PubNub(config) + clients._made.append(client) + return client + + +def only_message(seen): + eventually(lambda: a.eq(len(seen.messages), 1, 'messages received')) + return seen.messages[0].message diff --git a/tests/live/shared/file_sharing.py b/tests/live/shared/file_sharing.py new file mode 100644 index 00000000..b044265e --- /dev/null +++ b/tests/live/shared/file_sharing.py @@ -0,0 +1,86 @@ +"""Scenario data and helpers of the file-sharing page, shared by the sync and asyncio tests: literal resource names +(NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +import urllib.request +from pathlib import Path + + +NAMES = ['test_channel'] + + +FIXTURE = Path(__file__).resolve().parent.parent / 'fixtures' / 'sample.gif' + + +FIXTURE_BYTES = FIXTURE.read_bytes() + + +def channel_name(): + return 'ch1' + + +def upload(pubnub, channel=None, store=True): + """Seed a file outside the snippet markers. Returns the PNSendFileResult.""" + with open(FIXTURE, 'rb') as sample_file: + return pubnub.send_file().channel(channel or channel_name()).file_name('sample.gif') \ + .file_object(sample_file).should_store(store).sync().result + + +def remove(pubnub, *uploaded): + for item in uploaded: + try: + pubnub.delete_file().channel(channel_name()).file_id(item.file_id).file_name(item.name).sync() + except Exception as e: # cleanup must never hide the real failure + print('cleanup: could not delete a file (' + type(e).__name__ + ')') + + +def stored_file_messages(pubnub, *file_ids): + """File events read back from Message Persistence. A subscriber callback cannot be used, see the report: the SDK + raises AttributeError in models/subscription.py for every file event and the worker thread dies.""" + envelope = pubnub.fetch_messages().channels(channel_name()).include_meta(True).sync() + items = envelope.result.channels.get(channel_name(), []) + files = [item for item in items if isinstance(item.message, dict) and 'file' in item.message] + return [item for item in files if not file_ids or item.message['file']['id'] in file_ids] + + +def listed_ids(pubnub): + envelope = pubnub.list_files().channel(channel_name()).sync() + return [item['id'] for item in envelope.result.data] + + +def channel_name_async(): + return 'test_channel' + + +async def upload_async(pubnub, store=True): + """Seed a file outside the snippet markers. Returns the PNSendFileResult.""" + with open(FIXTURE, 'rb') as sample_file: + envelope = await pubnub.send_file().channel(channel_name_async()).file_name('sample.gif') \ + .file_object(sample_file).should_store(store).future() + return envelope.result + + +async def remove_async(pubnub, *uploaded): + for item in uploaded: + try: + await pubnub.delete_file().channel(channel_name_async()).file_id(item.file_id).file_name(item.name).future() + except Exception as e: # cleanup must never hide the real failure + print('cleanup: could not delete a file (' + type(e).__name__ + ')') + + +async def stored_file_messages_async(pubnub, *file_ids): + """File events read back from Message Persistence, because the SDK cannot deliver file events to listeners.""" + envelope = await pubnub.fetch_messages().channels(channel_name_async()).include_meta(True).future() + items = envelope.result.channels.get(channel_name_async(), []) + files = [item for item in items if isinstance(item.message, dict) and 'file' in item.message] + return [item for item in files if not file_ids or item.message['file']['id'] in file_ids] + + +async def listed_ids_async(pubnub): + envelope = await pubnub.list_files().channel(channel_name_async()).future() + return [item['id'] for item in envelope.result.data] + + +def fetch(url): + with urllib.request.urlopen(url, timeout=30) as served: + return served.status, served.read() diff --git a/tests/live/shared/message_actions.py b/tests/live/shared/message_actions.py new file mode 100644 index 00000000..0c1bf0ac --- /dev/null +++ b/tests/live/shared/message_actions.py @@ -0,0 +1,59 @@ +"""Scenario data and helpers of the message-actions page, shared by the sync and asyncio tests: literal resource names +(NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from pubnub.models.consumer.message_actions import PNMessageAction + +from support import assertions as a +from support.wait import eventually +from support.wait import aeventually + +NAMES = ['chats.room1'] + + +def publish_stored(client, channel, count=1): + """Publish count messages and wait until history returns them. Returns their timetokens, oldest first.""" + tokens = [int(client.publish().channel(channel).message({'n': i}).sync().result.timetoken) for i in range(count)] + + def stored(): + got = client.fetch_messages(channels=[channel], start=tokens[-1] + 1, end=tokens[0]).sync() + a.eq([int(i.timetoken) for i in got.result.channels.get(channel, [])], tokens, 'stored timetokens') + + eventually(stored, timeout=30, what='published messages stored') + return tokens + + +def add_action(client, channel, message_timetoken, value, action_type='reaction'): + action = PNMessageAction() + action.type = action_type + action.value = value + action.message_timetoken = message_timetoken + return client.add_message_action().channel(channel).message_action(action).sync().result + + +async def publish_stored_async(client, channel, count=1): + """Publish count messages and wait until history returns them. Returns their timetokens, oldest first.""" + tokens = [] + for i in range(count): + envelope = await client.publish().channel(channel).message({'n': i}).future() + tokens.append(int(envelope.result.timetoken)) + + async def stored(): + got = await client.fetch_messages(channels=[channel], start=tokens[-1] + 1, end=tokens[0]).future() + a.eq([int(i.timetoken) for i in got.result.channels.get(channel, [])], tokens, 'stored timetokens') + + await aeventually(stored, timeout=30, what='published messages stored') + return tokens + + +async def add_action_async(client, channel, message_timetoken, value, action_type='reaction'): + action = PNMessageAction() + action.type = action_type + action.value = value + action.message_timetoken = message_timetoken + return (await client.add_message_action().channel(channel).message_action(action).future()).result + + +async def remove_action(client, channel, message_timetoken, action_timetoken): + await client.remove_message_action(channel=channel, message_timetoken=message_timetoken, + action_timetoken=int(action_timetoken)).future() diff --git a/tests/live/shared/message_persistence.py b/tests/live/shared/message_persistence.py new file mode 100644 index 00000000..9fe726d1 --- /dev/null +++ b/tests/live/shared/message_persistence.py @@ -0,0 +1,118 @@ +"""Scenario data and helpers of the message-persistence page, shared by the sync and asyncio tests: literal resource +names (NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet +markers. Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync +name. +""" +import asyncio + +from support import assertions as a +from support.wait import eventually +from support.wait import aeventually + +NAMES = ['history_channel', 'history_channel_2', 'history_paging_channel', 'history_paging_channel_2'] + + +def seed(client, channel, count, **extra): + """Publish count messages one after the other and return [(message, timetoken)] oldest first.""" + seeded = [] + for index in range(count): + message = {'n': index, 'channel': channel} + builder = client.publish().channel(channel).message(message) + if extra.get('meta'): + builder = builder.meta(extra['meta']) + if extra.get('custom_message_type'): + builder = builder.custom_message_type(extra['custom_message_type']) + seeded.append((message, int(builder.sync().result.timetoken))) + return seeded + + +def seed_many(client, channel, count): + """Publish count messages one after the other and return their timetokens, oldest first. + + One at a time on purpose: 8 threads on one client returned the same timetoken for two publishes in a CI run, so the + expected values no longer matched what the service stored. A duplicate fails here, with the cause, not later as a + mismatch of two long lists.""" + tokens = [int(client.publish().channel(channel).message({'n': index}).sync().result.timetoken) + for index in range(count)] + a.eq(len(set(tokens)), count, f'every publish on {channel} returned its own timetoken') + return sorted(tokens) + + +def window(client, channel, newest, oldest, **kwargs): + """Fetch the seeded range: start is exclusive, so one above the newest. Returns the items oldest first.""" + envelope = client.fetch_messages(channels=[channel], start=newest + 1, end=oldest, **kwargs).sync() + return envelope.result.channels.get(channel, []) + + +def wait_stored(client, channel, timetokens): + def check(): + stored = [int(item.timetoken) for item in window(client, channel, max(timetokens), min(timetokens))] + a.eq(stored, sorted(timetokens), 'stored timetokens') + + eventually(check, timeout=30, what='seeded messages stored') + + +async def seed_async(client, channel, count, **extra): + """Publish count messages one after the other and return [(message, timetoken)] oldest first.""" + seeded = [] + for index in range(count): + message = {'n': index, 'channel': channel} + builder = client.publish().channel(channel).message(message) + if extra.get('meta'): + builder = builder.meta(extra['meta']) + if extra.get('custom_message_type'): + builder = builder.custom_message_type(extra['custom_message_type']) + seeded.append((message, int((await builder.future()).result.timetoken))) + return seeded + + +async def seed_parallel_async(client, channel, count, concurrency=20): + """Publish count messages, at most `concurrency` at a time. Only the timetokens matter, they come back sorted. + + No repeat after an error: a publish whose response was lost can already be stored, and a repeat would store it + twice. The cap keeps the number of requests in flight on one HTTP/2 connection low instead.""" + limit = asyncio.Semaphore(concurrency) + + async def one(index): + async with limit: + envelope = await client.publish().channel(channel).message({'n': index}).future() + if envelope.is_error(): + raise AssertionError(f'publish {index} failed: category={envelope.status.category} ' + f'error={envelope.status.error_data}') + return int(envelope.result.timetoken) + + return sorted(await asyncio.gather(*[one(i) for i in range(count)])) + + +async def window_async(client, channel, newest, oldest, **kwargs): + """Fetch the seeded range: start is exclusive, so one above the newest. Returns the items oldest first.""" + envelope = await client.fetch_messages(channels=[channel], start=newest + 1, end=oldest, **kwargs).future() + return envelope.result.channels.get(channel, []) + + +async def wait_stored_async(client, channel, timetokens): + async def check(): + stored = [int(item.timetoken) for item in await window_async(client, channel, max(timetokens), min(timetokens))] + a.eq(stored, sorted(timetokens), 'stored timetokens') + + await aeventually(check, timeout=30, what='seeded messages stored') + + +def paging_lines(pages): + """The text the history paging sample prints for these reference pages: (count, start, end, timetokens) per page.""" + lines = [] + for count, start, end, _ in pages: + lines += ['%d' % count, 'start %d' % start, 'end %d' % end] + return lines + + +def check_paging(lines, pages, tokens): + """The sample printed what the API holds, and every published message is on a page. + A publish that the SDK repeated after a transient error is stored twice, so the pages (read independently) are the + reference, not the list of publish timetokens.""" + a.eq(lines[:len(pages) * 3], paging_lines(pages), 'the pages the sample printed') + a.eq(lines[len(pages) * 3:], [''], 'nothing printed after the last page') + on_pages = {t for _, _, _, listed in pages for t in listed} + a.eq(sorted(set(tokens) - on_pages), [], 'published timetokens that are on no page') + a.eq(pages[0][0], 100, 'the first page holds the newest 100') + a.eq(pages[0][2], tokens[-1], 'the first page ends at the newest published message') diff --git a/tests/live/shared/mobile_push.py b/tests/live/shared/mobile_push.py new file mode 100644 index 00000000..799193dc --- /dev/null +++ b/tests/live/shared/mobile_push.py @@ -0,0 +1,107 @@ +"""Scenario data and helpers of the mobile-push page, shared by the sync and asyncio tests: literal resource names +(NAMES, read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from pubnub.enums import PNPushEnvironment, PNPushType + +from support import assertions as a +from support.wait import eventually +from support.wait import aeventually +from support.resources import APNS2_DEVICE + +NAMES = ['deviceId', 'unknown'] + + +TOPIC = 'myapptopic' + + +CHANNELS = ['ch1', 'ch2', 'ch3'] + + +def suffixed(channels): + return sorted(c for c in channels) + + +def fcm_device(): + return 'deviceId' + + +def registered(pubnub, push_type): + """Channels the service holds for the device on one gateway.""" + if push_type == PNPushType.APNS2: + envelope = pubnub.list_push_channels().push_type(push_type).device_id(APNS2_DEVICE) \ + .topic(TOPIC).environment(PNPushEnvironment.DEVELOPMENT).sync() + else: + envelope = pubnub.list_push_channels().push_type(push_type).device_id(fcm_device()).sync() + return sorted(envelope.result.channels) + + +def seed(pubnub, channels): + channels = suffixed(channels) + pubnub.add_channels_to_push().push_type(PNPushType.FCM).channels(channels).device_id(fcm_device()).sync() + pubnub.add_channels_to_push().push_type(PNPushType.APNS2).channels(channels).device_id(APNS2_DEVICE) \ + .topic(TOPIC).environment(PNPushEnvironment.DEVELOPMENT).sync() + + +def clear(pubnub): + """Remove the test tokens on every gateway and environment so that nothing outlives the run.""" + for push_type in (PNPushType.FCM, PNPushType.GCM): + try: + pubnub.remove_device_from_push().push_type(push_type).device_id(fcm_device()).sync() + except Exception as e: # cleanup must never hide the real failure + print('cleanup: could not clear a gateway (' + type(e).__name__ + ')') + for push_type in (PNPushType.APNS, PNPushType.APNS2): + for environment in (PNPushEnvironment.DEVELOPMENT, PNPushEnvironment.PRODUCTION): + try: + pubnub.remove_device_from_push().push_type(push_type).device_id(APNS2_DEVICE) \ + .topic(TOPIC).environment(environment).sync() + except Exception as e: + print('cleanup: could not clear a gateway (' + type(e).__name__ + ')') + + +def expect(pubnub, fcm, apns2, what): + eventually(lambda: a.eq(registered(pubnub, PNPushType.FCM), fcm, 'fcm ' + what)) + eventually(lambda: a.eq(registered(pubnub, PNPushType.APNS2), apns2, 'apns2 ' + what)) + + +async def registered_async(pubnub, push_type): + """Channels the service holds for the device on one gateway.""" + if push_type == PNPushType.APNS2: + envelope = await pubnub.list_push_channels().push_type(push_type).device_id(APNS2_DEVICE) \ + .topic(TOPIC).environment(PNPushEnvironment.DEVELOPMENT).future() + else: + envelope = await pubnub.list_push_channels().push_type(push_type).device_id(fcm_device()).future() + return sorted(envelope.result.channels) + + +async def seed_async(pubnub, channels): + channels = suffixed(channels) + await pubnub.add_channels_to_push().push_type(PNPushType.FCM).channels(channels).device_id(fcm_device()).future() + await pubnub.add_channels_to_push().push_type(PNPushType.APNS2).channels(channels).device_id(APNS2_DEVICE) \ + .topic(TOPIC).environment(PNPushEnvironment.DEVELOPMENT).future() + + +async def clear_async(pubnub): + """Remove the test tokens on every gateway and environment so that nothing outlives the run.""" + for push_type in (PNPushType.FCM, PNPushType.GCM): + try: + await pubnub.remove_device_from_push().push_type(push_type).device_id(fcm_device()).future() + except Exception as e: # cleanup must never hide the real failure + print('cleanup: could not clear a gateway (' + type(e).__name__ + ')') + for push_type in (PNPushType.APNS, PNPushType.APNS2): + for environment in (PNPushEnvironment.DEVELOPMENT, PNPushEnvironment.PRODUCTION): + try: + await pubnub.remove_device_from_push().push_type(push_type).device_id(APNS2_DEVICE) \ + .topic(TOPIC).environment(environment).future() + except Exception as e: + print('cleanup: could not clear a gateway (' + type(e).__name__ + ')') + + +async def expect_async(pubnub, fcm, apns2, what): + async def fcm_state(): + a.eq(await registered_async(pubnub, PNPushType.FCM), fcm, 'fcm ' + what) + + async def apns2_state(): + a.eq(await registered_async(pubnub, PNPushType.APNS2), apns2, 'apns2 ' + what) + await aeventually(fcm_state) + await aeventually(apns2_state) diff --git a/tests/live/shared/objects.py b/tests/live/shared/objects.py new file mode 100644 index 00000000..2f194ca2 --- /dev/null +++ b/tests/live/shared/objects.py @@ -0,0 +1,416 @@ +"""Scenario data and helpers of the objects page, shared by the sync and asyncio tests: literal resource names (NAMES, +read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +import re + +from pubnub.callbacks import SubscribeCallback +from pubnub.enums import PNStatusCategory +from pubnub.exceptions import PubNubAsyncioException, PubNubException +from pubnub.models.consumer.objects_v2.memberships import PNChannelMembership +from pubnub.models.consumer.objects_v2.channel_members import PNUUID + +from support import assertions as a +from support import cleanup as live_cleanup +from support import redact +from support.wait import aeventually, asettled, eventually, settled + +NAMES = [ + 'channel_id', + 'channel_id_named', + 'doc_channel_a', + 'doc_channel_b', + 'doc_channel_c', + 'doc_missing', + 'doc_missing_channel', + 'doc_other', + 'doc_type', + 'doc_user_a', + 'doc_user_b', + 'doc_user_c', + 'some_uuid', + 'some_uuid_extra', + 'some_uuid_named', + 'some_uuid_with_custom', + 'somechannel', + 'somechannel_extra', + 'somechannel_with_custom', +] + + +UUID_FIELDS = { + 'name': 'Some Name', + 'status': 'Active', + 'type': 'User', + 'email': 'test@example.com', + 'profileUrl': 'http://example.com', + 'externalId': '1234567890', +} + + +class AppContextEvents(SubscribeCallback): + """Collects App Context events. + + The sync SDK stops its message worker with an AttributeError right after it hands the first App Context event + to the listeners (models/subscription.py:314-324). A watcher therefore sees exactly one event, so a step + creates one watcher per change it wants to observe. + """ + def __init__(self): + self.categories = [] + self.items = [] + + def status(self, pubnub, status): + self.categories.append(status.category) + + def message(self, pubnub, message): + pass + + def presence(self, pubnub, presence): + pass + + def uuid(self, pubnub, uuid): + self.items.append(('uuid', uuid.event, uuid.data)) + + def channel(self, pubnub, channel): + self.items.append(('channel', channel.event, channel.data)) + + def membership(self, pubnub, membership): + self.items.append(('membership', membership.event, membership.data)) + + +def watch(clients, *channels): + """A second client that listens on the given channels. Returns after it is connected.""" + client = clients.sync('open', 'watcher') + seen = AppContextEvents() + client.subscribed_by_suite = True + client.add_listener(seen) + client.subscribe().channels(list(channels)).execute() + eventually(lambda: a.ok(PNStatusCategory.PNConnectedCategory in seen.categories, 'not connected yet'), + timeout=15, what='watcher connected') + return seen + + +def first_event(seen): + eventually(lambda: a.ok(len(seen.items) >= 1, 'no App Context event yet'), timeout=20, what='App Context event') + return seen.items[0] + + +def quiet_404(call): + """Run a cleanup call. A missing object is fine, any other error is not.""" + try: + return call() + except PubNubException as e: + if '404' not in str(e): + raise + return None + + +def attempt(call): + """Run a read. An SDK error (for example the 404 of a replica that has not seen a create yet) becomes an + AssertionError, so that eventually() and settled() retry it.""" + try: + return call() + except PubNubException as e: + raise AssertionError(redact.scrub(f'read failed: {e}')) + + +def settled_read(call, check, what, timeout=30): + """Read until `check` passes on SETTLED.passes consecutive reads, then return the last result. App Context reads + are served by replicas that lag a write, and two reads in a row can hit different replicas: a precondition that + passes once can still be stale on the next read (the sample's).""" + def once(): + value = attempt(call) + check(value) + return value + return settled(once, timeout=timeout, what=what) + + +def absent(read, what='object reports 404'): + """The read raises a 404 on consecutive reads (every replica has seen the delete).""" + settled(lambda: a.raises(PubNubException, read, match='404'), timeout=30, what=what) + + +def _listed(call, key): + found = quiet_404(call) + return {item[key]['id'] for item in (found.result.data if found else []) or []} + + +def cleanup(pubnub, uuids=(), channels=()): + """Remove the memberships of both sides, then the metadata objects, then wait until consecutive reads agree. + + Both sides are removed for every page name, not only for what a read returns: a read right after a write can come + from a lagging replica and miss a membership, which then outlives the test (CI saw some_uuid_extra and channel_id + leftovers). Removing a membership that does not exist is not an error. + """ + names = set(NAMES) + for uid in uuids: + listed = _listed(lambda: pubnub.get_memberships(uuid=uid, limit=100).sync(), 'channel') + targets = sorted(listed | names) + quiet_404(lambda: pubnub.remove_memberships( + uuid=uid, channel_memberships=[PNChannelMembership.channel(c) for c in targets]).sync()) + for channel in channels: + listed = _listed(lambda: pubnub.get_channel_members(channel=channel, limit=100).sync(), 'uuid') + targets = sorted(listed | names) + quiet_404(lambda: pubnub.remove_channel_members( + channel=channel, uuids=[PNUUID.uuid(u) for u in targets]).sync()) + for channel in channels: + quiet_404(lambda: pubnub.remove_channel_metadata(channel=channel).sync()) + for uid in uuids: + quiet_404(lambda: pubnub.remove_uuid_metadata(uuid=uid).sync()) + + def clean(): + for uid in uuids: + a.eq(sorted(_listed(lambda: pubnub.get_memberships(uuid=uid, limit=100).sync(), 'channel') & names), [], + f'memberships of {uid} left') + a.raises(PubNubException, lambda: pubnub.get_uuid_metadata(uuid=uid).sync(), match='404') + for channel in channels: + members = _listed(lambda: pubnub.get_channel_members(channel=channel, limit=100).sync(), 'uuid') + a.eq(sorted(members & names), [], f'members of {channel} left') + a.raises(PubNubException, lambda: pubnub.get_channel_metadata(channel=channel).sync(), match='404') + settled(clean, timeout=45, what='App Context objects removed') + + +def fresh(pubnub, uuids=(), channels=()): + """Precondition: no membership, member or metadata of these names is left, on consecutive reads.""" + cleanup(pubnub, uuids, channels) + + +def record(uuids=(), channels=()): + for uid in uuids: + live_cleanup.record('uuid_metadata', uid) + for channel in channels: + live_cleanup.record('channel_metadata', channel) + + +def ids(items): + return [item['id'] for item in items] + + +def gone(read): + """The read raises a 404 once the object is removed, on consecutive reads.""" + absent(read) + + +CUSTOM_1 = {'key3': 'val1', 'key4': 'val2'} + + +CUSTOM_2 = {'key5': 'val1', 'key6': 'val2'} + + +def channel_ids(items): + return [item['channel']['id'] for item in items] + + +def member_ids(items): + return [item['uuid']['id'] for item in items] + + +def by_channel(items): + return {item['channel']['id']: item for item in items} + + +def by_member(items): + return {item['uuid']['id']: item for item in items} + + +def seed_channels(pubnub, plain, with_custom): + pubnub.set_channel_metadata(channel=plain, name='some name').sync() + pubnub.set_channel_metadata(channel=with_custom, name='some name with custom', custom=CUSTOM_1).sync() + + +def seed_users(pubnub, plain, with_custom): + pubnub.set_uuid_metadata(uuid=plain, name='some name').sync() + pubnub.set_uuid_metadata(uuid=with_custom, name='some name with custom', custom=CUSTOM_1).sync() + + +def seed_memberships(pubnub, uid, plain, with_custom): + pubnub.set_memberships(uuid=uid, channel_memberships=[ + PNChannelMembership.channel(plain), PNChannelMembership.channel_with_custom(with_custom, CUSTOM_2)]).sync() + + +def seed_one_membership(pubnub, uid, with_custom): + pubnub.set_memberships(uuid=uid, channel_memberships=[ + PNChannelMembership.channel_with_custom(with_custom, CUSTOM_2)]).sync() + + +def seed_one_member(pubnub, channel, with_custom): + pubnub.set_channel_members(channel=channel, uuids=[PNUUID.uuid_with_custom(with_custom, CUSTOM_2)]).sync() + + +def seed_members(pubnub, channel, plain, with_custom): + pubnub.set_channel_members(channel=channel, uuids=[ + PNUUID.uuid(plain), PNUUID.uuid_with_custom(with_custom, CUSTOM_2)]).sync() + + +def check_memberships(items, plain, with_custom): + """Both memberships with the details MembershipIncludes(custom, channel, channel_custom) asks for.""" + a.eq(sorted(channel_ids(items)), sorted([plain, with_custom])) + found = by_channel(items) + a.eq(found[plain]['custom'], None, 'plain membership has no custom') + a.eq(found[with_custom]['custom'], CUSTOM_2, 'membership custom') + a.eq(found[plain]['channel']['name'], 'some name') + a.eq(found[with_custom]['channel']['custom'], CUSTOM_1, 'channel custom') + a.eq(found[with_custom]['channel']['name'], 'some name with custom') + a.ok(found[plain]['eTag'] and found[plain]['updated'], 'eTag and updated are returned') + + +def check_members(items, plain, with_custom): + a.eq(sorted(member_ids(items)), sorted([plain, with_custom])) + found = by_member(items) + a.eq(found[plain]['custom'], None, 'plain member has no custom') + a.eq(found[with_custom]['custom'], CUSTOM_2, 'member custom') + a.eq(found[plain]['uuid']['name'], 'some name') + a.eq(found[with_custom]['uuid']['custom'], CUSTOM_1, 'user custom') + a.eq(found[with_custom]['uuid']['name'], 'some name with custom') + + +# Coroutine twins for the asyncio tests. The asyncio client does not raise on an HTTP error, future() resolves with a +# PubNubAsyncioException instead, so the twins turn it into an AssertionError (or look at it, where an error is wanted). + +async def watch_async(aclients, *channels): + """A second asyncio client that listens on the given channels. Returns after it is connected.""" + client = aclients.asyncio('open', 'watcher') + seen = AppContextEvents() + client.subscribed_by_suite = True + client.add_listener(seen) + client.subscribe().channels(list(channels)).execute() + await aeventually(lambda: a.ok(PNStatusCategory.PNConnectedCategory in seen.categories, 'not connected yet'), + timeout=15, what='watcher connected') + return seen + + +async def first_event_async(seen): + await aeventually(lambda: a.ok(len(seen.items) >= 1, 'no App Context event yet'), timeout=20, + what='App Context event') + return seen.items[0] + + +def checked(envelope): + """The envelope of a future(), or an AssertionError when the call resolved with an error.""" + if isinstance(envelope, PubNubAsyncioException): + raise AssertionError(redact.scrub(f'call failed: {envelope}')) + return envelope + + +def _is_404(failed): + return '404' in str(failed) or getattr(failed.status, 'status_code', None) == 404 + + +async def quiet_404_async(call): + """Run a cleanup call. A missing object is fine, any other error is not.""" + result = await call() + if isinstance(result, PubNubAsyncioException): + if not _is_404(result): + raise AssertionError(redact.scrub(f'cleanup call failed: {result}')) + return None + return result + + +async def attempt_async(call): + """Run a read. An error (for example the 404 of a replica that has not seen a create yet) becomes an + AssertionError, so that aeventually() and asettled() retry it.""" + result = await call() + if isinstance(result, PubNubAsyncioException): + raise AssertionError(redact.scrub(f'read failed: {result}')) + return result + + +async def expect_error_async(call, match): + """The call resolves with an error that matches `match`. Returns the error.""" + result = await call() + if not isinstance(result, PubNubAsyncioException): + raise AssertionError('the call did not resolve with an error') + text = redact.scrub(f'{result} {getattr(result.status, "status_code", "")}') + if not re.search(match, text): + raise AssertionError(f'error {text!r} does not match {match!r}') + return result + + +async def settled_read_async(call, check, what, timeout=30): + """settled_read() for a coroutine function.""" + async def once(): + value = await attempt_async(call) + check(value) + return value + return await asettled(once, timeout=timeout, what=what) + + +async def absent_async(read, what='object reports 404'): + await asettled(lambda: expect_error_async(read, '404'), timeout=30, what=what) + + +async def _listed_async(call, key): + found = await quiet_404_async(call) + return {item[key]['id'] for item in (found.result.data if found else []) or []} + + +async def cleanup_async(pubnub, uuids=(), channels=()): + """cleanup() for an asyncio client.""" + names = set(NAMES) + for uid in uuids: + listed = await _listed_async(lambda: pubnub.get_memberships(uuid=uid, limit=100).future(), 'channel') + targets = sorted(listed | names) + await quiet_404_async(lambda: pubnub.remove_memberships( + uuid=uid, channel_memberships=[PNChannelMembership.channel(c) for c in targets]).future()) + for channel in channels: + listed = await _listed_async(lambda: pubnub.get_channel_members(channel=channel, limit=100).future(), 'uuid') + targets = sorted(listed | names) + await quiet_404_async(lambda: pubnub.remove_channel_members( + channel=channel, uuids=[PNUUID.uuid(u) for u in targets]).future()) + for channel in channels: + await quiet_404_async(lambda: pubnub.remove_channel_metadata(channel=channel).future()) + for uid in uuids: + await quiet_404_async(lambda: pubnub.remove_uuid_metadata(uuid=uid).future()) + + async def clean(): + for uid in uuids: + left = await _listed_async(lambda: pubnub.get_memberships(uuid=uid, limit=100).future(), 'channel') + a.eq(sorted(left & names), [], f'memberships of {uid} left') + await expect_error_async(lambda: pubnub.get_uuid_metadata(uuid=uid).future(), '404') + for channel in channels: + members = await _listed_async(lambda: pubnub.get_channel_members(channel=channel, limit=100).future(), + 'uuid') + a.eq(sorted(members & names), [], f'members of {channel} left') + await expect_error_async(lambda: pubnub.get_channel_metadata(channel=channel).future(), '404') + await asettled(clean, timeout=45, what='App Context objects removed') + + +async def fresh_async(pubnub, uuids=(), channels=()): + """Precondition: no membership, member or metadata of these names is left, on consecutive reads.""" + await cleanup_async(pubnub, uuids, channels) + + +async def gone_async(read): + """The read resolves with a 404 once the object is removed, on consecutive reads.""" + await absent_async(read) + + +async def seed_channels_async(pubnub, plain, with_custom): + checked(await pubnub.set_channel_metadata(channel=plain, name='some name').future()) + checked(await pubnub.set_channel_metadata(channel=with_custom, name='some name with custom', + custom=CUSTOM_1).future()) + + +async def seed_users_async(pubnub, plain, with_custom): + checked(await pubnub.set_uuid_metadata(uuid=plain, name='some name').future()) + checked(await pubnub.set_uuid_metadata(uuid=with_custom, name='some name with custom', custom=CUSTOM_1).future()) + + +async def seed_memberships_async(pubnub, uid, plain, with_custom): + checked(await pubnub.set_memberships(uuid=uid, channel_memberships=[ + PNChannelMembership.channel(plain), PNChannelMembership.channel_with_custom(with_custom, CUSTOM_2)]).future()) + + +async def seed_one_membership_async(pubnub, uid, with_custom): + checked(await pubnub.set_memberships(uuid=uid, channel_memberships=[ + PNChannelMembership.channel_with_custom(with_custom, CUSTOM_2)]).future()) + + +async def seed_one_member_async(pubnub, channel, with_custom): + checked(await pubnub.set_channel_members(channel=channel, uuids=[ + PNUUID.uuid_with_custom(with_custom, CUSTOM_2)]).future()) + + +async def seed_members_async(pubnub, channel, plain, with_custom): + checked(await pubnub.set_channel_members(channel=channel, uuids=[ + PNUUID.uuid(plain), PNUUID.uuid_with_custom(with_custom, CUSTOM_2)]).future()) diff --git a/tests/live/shared/presence.py b/tests/live/shared/presence.py new file mode 100644 index 00000000..05dc5d03 --- /dev/null +++ b/tests/live/shared/presence.py @@ -0,0 +1,84 @@ +"""Scenario data and helpers of the presence page, shared by the sync and asyncio tests: literal resource names (NAMES, +read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from support import assertions as a +from support.clients import BaseClients, config +from support.wait import PRESENCE_TIMEOUT, settled + +NAMES = ['cg2', 'cg3', 'gr1', 'gr2', 'gr3', 'grouped_1', 'grouped_2', 'grouped_3', 'some-other-uuid', 'such_uuid'] + + +class Printed: + """Everything the docs code printed so far.""" + + def __init__(self, capsys): + self._capsys = capsys + self._parts = [] + + def text(self): + self._parts.append(self._capsys.readouterr().out) + return ''.join(self._parts) + + +def occupants_of(here_now, channel): + """uuids of one channel in a PNHereNowResult, sorted. The result holds a list of PNHereNowChannelData.""" + found = [c for c in here_now.result.channels if c.channel_name == channel] + return sorted(o.uuid for o in found[0].occupants) if found and found[0].occupants is not None else None + + +def occupancy_of(here_now, channel): + found = [c for c in here_now.result.channels if c.channel_name == channel] + return found[0].occupancy if found else None + + +def own_occupants(here_now, channel, mine): + """The test's own user IDs that here_now lists on a channel, sorted. Shared channels are persistent, so other + occupants (a user ID of an earlier test whose leave the service has not applied yet) are ignored.""" + return sorted(set(occupants_of(here_now, channel) or []) & set(mine)) + + +def consistent(here_now): + """Counts of one here_now response agree with its own lists (when it lists the user IDs).""" + for c in here_now.result.channels: + if c.occupants: + a.eq(c.occupancy, len(c.occupants), f'occupancy of {c.channel_name} counts its listed occupants') + a.eq(here_now.result.total_occupancy, sum(c.occupancy for c in here_now.result.channels), 'total occupancy') + + +def not_present(channel, user_ids): + """Precondition of a join test: the user IDs are not occupants of the channel, on consecutive here_now reads. + + The service emits a join only for a user ID that is not already an occupant, and a user ID of an earlier test + stays listed until its leave is applied or it times out. An explicit leave first, then the wait. Blocking: the + asyncio tests call it too, before they start the subscriptions it concerns. + """ + from pubnub.pubnub import PubNub + BaseClients.send_leaves([('open', uid, [channel], []) for uid in user_ids]) + reader = PubNub(config('open', 'presence_check')) + try: + def gone(): + here = reader.here_now().channels(channel).include_uuids(True).sync() + a.eq(own_occupants(here, channel, user_ids), [], f'{", ".join(user_ids)} still listed on {channel}') + settled(gone, timeout=PRESENCE_TIMEOUT, what=f'user IDs not present on {channel}') + finally: + reader.stop() + + +def present(channels, user_id): + """Precondition of a test that sets state: the user ID is an occupant of every channel, on consecutive reads. + + The service applies set_state() only to channels where the user ID is already present. A subscribe is connected + before its presence join is registered, and a fast client sets the state in between, which is then never applied. + Blocking: the asyncio tests call it too, before the sample. + """ + from pubnub.pubnub import PubNub + reader = PubNub(config('open', 'presence_check')) + try: + def listed(): + for channel in channels: + here = reader.here_now().channels(channel).include_uuids(True).sync() + a.eq(own_occupants(here, channel, [user_id]), [user_id], f'{user_id} not listed on {channel} yet') + settled(listed, timeout=PRESENCE_TIMEOUT, what=f'{user_id} present on {", ".join(channels)}') + finally: + reader.stop() diff --git a/tests/live/shared/publish.py b/tests/live/shared/publish.py new file mode 100644 index 00000000..93ca03e9 --- /dev/null +++ b/tests/live/shared/publish.py @@ -0,0 +1,16 @@ +"""Scenario data and helpers of the publish page, shared by the sync and asyncio tests: literal resource names (NAMES, +read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from support import assertions as a + +NAMES = [] + + +async def history_of(pubnub, channel): + fetched = await pubnub.fetch_messages(channels=[channel]).future() + return [item.message for item in fetched.result.channels.get(channel, [])] + + +async def stored_has(pubnub, channel, wanted): + a.contains(await history_of(pubnub, channel), wanted, 'message is stored in history') diff --git a/tests/live/shared/subscribe.py b/tests/live/shared/subscribe.py new file mode 100644 index 00000000..6f2e3470 --- /dev/null +++ b/tests/live/shared/subscribe.py @@ -0,0 +1,98 @@ +"""Scenario data and helpers of the subscribe page, shared by the sync and asyncio tests: literal resource names (NAMES, +read by the janitor through support/resources.py) and the helpers the tests call outside the snippet markers. +Coroutine twins of a sync helper carry an "_async" suffix, and the asyncio tests import them under the sync name. +""" +from pubnub.enums import PNStatusCategory + +from support import assertions as a +from support.listen import Collector +from support.wait import eventually +from support.listen import Collector +from support.wait import aeventually + +NAMES = [ + 'awesome_channel_group', + 'bar', + 'cg_1', + 'channelGroupName', + 'channelMetadata', + 'group-test', + 'grouped_channel', + 'grouped_one', + 'grouped_two', + 'my_channel1', + 'my_channel2', + 'my_group1', + 'my_group2', + 'user_metadata', +] + + +def attach(client): + """Add a collector to a client without subscribing. The docs code does the subscribing.""" + collector = Collector() + client.subscribed_by_suite = True + client.add_listener(collector) + return collector + + +def connected(collector): + eventually(lambda: a.ok(PNStatusCategory.PNConnectedCategory in collector.categories, 'not connected yet'), + what='PNConnectedCategory') + + +def texts(collector): + return [m.message for m in collector.messages] + + +class AppContextCollector(Collector): + """Collector that also keeps App Context events.""" + def __init__(self): + super().__init__() + self.channel_events = [] + self.uuid_events = [] + + def channel(self, pubnub, channel): + with self._lock: + self.channel_events.append(channel) + + def uuid(self, pubnub, uuid): + with self._lock: + self.uuid_events.append(uuid) + + +class Printed: + """Everything the docs listeners printed so far. Callbacks run on SDK threads, capsys sees their output.""" + + def __init__(self, capsys): + self._capsys = capsys + self._parts = [] + + def text(self): + self._parts.append(self._capsys.readouterr().out) + return ''.join(self._parts) + + +class StatusCollector(Collector): + """Collector that keeps the status objects, not only their categories.""" + + def __init__(self): + super().__init__() + self.statuses = [] + + def status(self, pubnub, status): + super().status(pubnub, status) + with self._lock: + self.statuses.append(status) + + +def attach_status(client): + collector = StatusCollector() + client.subscribed_by_suite = True + client.add_listener(collector) + return collector + + +async def connected_async(collector): + await aeventually(lambda: a.ok(PNStatusCategory.PNConnectedCategory in collector.categories, 'not connected yet'), + what='PNConnectedCategory') diff --git a/tests/live/snippet-exceptions.json b/tests/live/snippet-exceptions.json new file mode 100644 index 00000000..77f7d493 --- /dev/null +++ b/tests/live/snippet-exceptions.json @@ -0,0 +1,11 @@ +{ + "$comment": "Hand maintained. exceptions: docs embeds from pubnub/python that no test runs, with a reason (path under tests/live/, ids absent means every embed of the path). one_sided: pages that exist in one docset only, with a reason. cli.py docs-check reads exceptions, the lint checks the shape.", + "exceptions": [], + "one_sided": [ + { + "docset": "sync", + "page": "test_encryption.py", + "reason": "The asyncio docset has no encryption page. The crypto module is configured the same way for both clients." + } + ] +} diff --git a/tests/live/support/__init__.py b/tests/live/support/__init__.py new file mode 100644 index 00000000..4f6efce6 --- /dev/null +++ b/tests/live/support/__init__.py @@ -0,0 +1,15 @@ +"""Shared support package of the live tier (tests/live/README.md). Serves the sync and the asyncio docset. + +Importing it puts the repository root first on the import path, so the tier always tests the checkout and never an +installed build of the SDK. +""" +import sys +from pathlib import Path + +LIVE_DIR = Path(__file__).resolve().parent.parent +REPO_ROOT = LIVE_DIR.parent.parent +LIVE_REL = 'tests/live' +DOCSETS = ('sync', 'asyncio') + +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) diff --git a/tests/live/support/assertions.py b/tests/live/support/assertions.py new file mode 100644 index 00000000..778b5493 --- /dev/null +++ b/tests/live/support/assertions.py @@ -0,0 +1,79 @@ +"""Assertion helpers. Plain functions that raise AssertionError, no recorder: the marker lint (rule H2) proves +statically that every test asserts after its snippet. + +The asyncio rule: `await endpoint.future()` returns a PubNubAsyncioException instead of raising +(pubnub/pubnub_asyncio.py, request_future), so asyncio tests check the envelope with assert_ok(). +""" +import re + +from pubnub.exceptions import PubNubAsyncioException, PubNubException + + +def ok(condition, message='condition is false'): + if not condition: + raise AssertionError(message) + + +def eq(actual, expected, message=''): + if actual != expected: + raise AssertionError(f'{message} expected {expected!r}, got {actual!r}'.strip()) + + +def contains(collection, item, message=''): + if item not in collection: + raise AssertionError(f'{message} {item!r} not in {collection!r}'.strip()) + + +def not_contains(collection, item, message=''): + if item in collection: + raise AssertionError(f'{message} {item!r} unexpectedly in {collection!r}'.strip()) + + +def timetoken(value, message='timetoken'): + """A timetoken is a string of 17 digits (publish) or a digit string for older values.""" + if not isinstance(value, (str, int)) or not re.fullmatch(r'\d{16,19}', str(value)): + raise AssertionError(f'{message}: {value!r} is not a timetoken') + + +assert_timetoken = timetoken + + +def raises(exc_type, fn, *args, match=None, **kwargs): + try: + fn(*args, **kwargs) + except exc_type as e: + if match and not re.search(match, str(e)): + raise AssertionError(f'error {e!r} does not match {match!r}') + return e + raise AssertionError(f'{exc_type.__name__} was not raised') + + +def assert_ok(envelope, message='call failed'): + """An envelope of .sync(), .future() or a pn_async callback status is not an error. Returns the envelope.""" + if isinstance(envelope, PubNubAsyncioException): + raise AssertionError(f'{message}: {envelope}') + status = getattr(envelope, 'status', envelope) + if status is not None and hasattr(status, 'is_error') and status.is_error(): + raise AssertionError(f'{message}: {getattr(status, "error_data", None)}') + return envelope + + +def raises_pubnub(fn, *args, status_code=None, category=None, **kwargs): + """fn raises PubNubException (sync) with the given status code or status category. Returns the exception.""" + try: + fn(*args, **kwargs) + except PubNubException as e: + if status_code is not None and e.get_status_code() != status_code: + raise AssertionError(f'expected status code {status_code}, got {e.get_status_code()}: {e}') + if category is not None and getattr(getattr(e, 'status', None), 'category', None) != category: + raise AssertionError(f'expected category {category}, got {getattr(e.status, "category", None)}') + return e + raise AssertionError('PubNubException was not raised') + + +def assert_server_time(value, slack_seconds=600): + """A server time in 10 ns units close to this machine's clock.""" + import time + timetoken(value, 'server time') + if abs(int(value) / 1e7 - time.time()) > slack_seconds: + raise AssertionError(f'server time {value} is more than {slack_seconds}s away from the local clock') diff --git a/tests/live/support/cleanup.py b/tests/live/support/cleanup.py new file mode 100644 index 00000000..6a63a76e --- /dev/null +++ b/tests/live/support/cleanup.py @@ -0,0 +1,67 @@ +"""Cleanup registry: cleanup_after_test(label, fn) runs fn after the test body, newest first, before the test's clients +stop. A 404 is silent, any other failure is printed (redacted) and never hides the test result. + +record(kind, name) registers the removal of one resource the test created. Kinds: channel_group, history, +uuid_metadata, channel_metadata. +""" +from pubnub.exceptions import PubNubException + +from . import redact + +_pending = [] + + +def cleanup_after_test(label, fn): + _pending.append((label, fn)) + + +def _is_404(error): + return isinstance(error, PubNubException) and (error.get_status_code() == 404 or '404' in str(error)) + + +def run_cleanups(): + """Run and clear every registered cleanup. Never raises.""" + try: + while _pending: + label, fn = _pending.pop() + try: + fn() + except Exception as error: # a cleanup must never replace the test's own result + if not _is_404(error): + print(redact.scrub(f'cleanup {label!r} failed: {type(error).__name__}: {error}')) + finally: + stop_helper() + + +def _helper(): + global _client + if _client is None: + from .clients_sync import SyncClients + _client = SyncClients().sync('open', 'cleanup') + return _client + + +_client = None + + +def stop_helper(): + global _client + if _client is not None: + _client.stop() + _client = None + + +def record(kind, name): + """Register the removal of a resource of the open keyset that the test created.""" + if kind == 'channel_group': + cleanup_after_test(f'remove channel group {name}', + lambda: _helper().remove_channel_group().channel_group(name).sync()) + elif kind == 'history': + cleanup_after_test(f'delete history of {name}', lambda: _helper().delete_messages().channel(name).sync()) + elif kind == 'uuid_metadata': + cleanup_after_test(f'remove user metadata {name}', lambda: _helper().remove_uuid_metadata(uuid=name).sync()) + elif kind == 'channel_metadata': + cleanup_after_test(f'remove channel metadata {name}', + lambda: _helper().remove_channel_metadata(channel=name).sync()) + else: + raise ValueError(f'unknown cleanup kind {kind!r}') diff --git a/tests/live/support/clients.py b/tests/live/support/clients.py new file mode 100644 index 00000000..b7c26152 --- /dev/null +++ b/tests/live/support/clients.py @@ -0,0 +1,116 @@ +"""Client configuration shared by both docsets. The client layers are clients_sync.py and clients_asyncio.py. + +Roles: 'open' (no Access Manager), 'pam' (Access Manager keyset, with the secret key unless secret=False). User ids are +the literal names the tests pass in, there is no run suffix. +""" +import threading +import time + +from pubnub.pnconfiguration import PNConfiguration + +from . import env + +UNREACHABLE_ORIGIN = '127.0.0.1:1' + + +PRESENCE_TIMEOUT = 20 + + +def config(role='open', user_id=None, secret=True): + keys = env.require(role) + cfg = PNConfiguration() + prefix = 'PAM_' if role == 'pam' else '' + cfg.publish_key = keys[prefix + 'PUBLISH_KEY'] + cfg.subscribe_key = keys[prefix + 'SUBSCRIBE_KEY'] + if role == 'pam' and secret: + cfg.secret_key = keys['PAM_SECRET_KEY'] + cfg.user_id = user_id or 'user' + # Request threads default to non-daemon (pubnub/pnconfiguration.py, daemon = False). A long poll cannot be + # interrupted by stop(), so it would hold the process open for up to 310 seconds. Helper clients set daemon=True, + # so that the lingering thread check sees only real leaks. + cfg.daemon = True + # A client that stops without a leave stays an occupant of a shared channel for the presence timeout (default + # 300 s), and the next test would count it. A short presence timeout lets it drop out between tests. + cfg.set_presence_timeout(PRESENCE_TIMEOUT) + return cfg + + +def unreachable_config(role='open', user_id='unreachable'): + """A configuration whose origin refuses every connection (no request leaves the machine).""" + cfg = config(role, user_id) + cfg.origin = UNREACHABLE_ORIGIN + cfg.ssl = False + return cfg + + +class BaseClients: + """Hands out clients of one docset and stops them all after the test. Subclasses build the client type.""" + + client_class = None + + def __init__(self): + self._made = [] + self._owners = {} + + def make(self, role='open', user_id=None, secret=True): + client = self.client_class(config(role, user_id, secret)) + self._made.append(client) + self._owners[id(client)] = (role, user_id or 'user') + return client + + def subscriptions_of(self, client): + """(role, user ID, channels, groups) a client is subscribed to, read before it unsubscribes. None if unknown.""" + owner = self._owners.get(id(client)) + if owner is None: + return None + try: + channels = [c for c in client.get_subscribed_channels() if not c.endswith('-pnpres')] + groups = [g for g in client.get_subscribed_channel_groups() if not g.endswith('-pnpres')] + except Exception: # a client that never subscribed has no subscription manager state (SDK finding) + return None + return (*owner, channels, groups) if channels or groups else None + + @staticmethod + def send_leaves(pending): + """An explicit leave per client. A client that stops without unsubscribing sends no leave (stop() never + does), and one that stays an occupant makes the next test miss the join event of the same user ID.""" + from pubnub.endpoints.presence.leave import Leave + from pubnub.pubnub import PubNub + for role, user, channels, groups in pending: + leaver = PubNub(config(role, user)) + try: + request = Leave(leaver) + if channels: + request.channels(channels) + if groups: + request.channel_groups(groups) + request.sync() + except Exception: # best effort: the janitor and the presence timeout are the backstop + pass + finally: + leaver.stop() + + def track(self, client): + """Stop a client the test built itself (for example from a sample's own configuration). + Its later request threads are daemon threads, so a long poll that is still in flight cannot hold the process.""" + client.config.daemon = True + self._made.append(client) + return client + + def open(self, user_id=None): + return self.make('open', user_id) + + def pam(self, user_id=None, secret=True): + return self.make('pam', user_id, secret) + + config = staticmethod(config) + + +def lingering_threads(wait=10.0): + """Names of non-daemon threads that are still alive after waiting. The Python analog of an open handle check.""" + deadline = time.monotonic() + wait + while True: + alive = [t for t in threading.enumerate() if t is not threading.main_thread() and not t.daemon and t.is_alive()] + if not alive or time.monotonic() >= deadline: + return [t.name for t in alive] + time.sleep(0.25) diff --git a/tests/live/support/clients_asyncio.py b/tests/live/support/clients_asyncio.py new file mode 100644 index 00000000..9de22000 --- /dev/null +++ b/tests/live/support/clients_asyncio.py @@ -0,0 +1,34 @@ +"""Client layer of the asyncio docset: PubNubAsyncio clients (pubnub/pubnub_asyncio.py, EventEngineSubscriptionManager +by default). stop() is a coroutine, so close() must run on the test's own event loop.""" +import asyncio + +from pubnub.pubnub_asyncio import PubNubAsyncio +from .clients import BaseClients + + +class AsyncioClients(BaseClients): + client_class = PubNubAsyncio + + def asyncio(self, role='open', user_id=None, secret=True): + """An asyncio client for a role and user ID: aclients.asyncio('open', 'publisher').""" + return self.make(role, user_id, secret) + + async def close(self): + pending = [x for x in (self.subscriptions_of(c) for c in self._made if isinstance(c, PubNubAsyncio)) if x] + for client in self._made: + if not isinstance(client, PubNubAsyncio): + continue + try: + # Always leave: a sample can subscribe without the test knowing, and a client that stops without + # a leave stays an occupant of the shared channel until the presence timeout. + # unsubscribe_all() raises AttributeError on a client that never subscribed (SDK finding) + try: + client.unsubscribe_all() + # The leave request is a fire-and-forget task: let it run before stop() cancels pending tasks. + await asyncio.sleep(1) + except AttributeError: + pass + finally: + await client.stop() + self.send_leaves(pending) + self._made = [] diff --git a/tests/live/support/clients_sync.py b/tests/live/support/clients_sync.py new file mode 100644 index 00000000..a091ef73 --- /dev/null +++ b/tests/live/support/clients_sync.py @@ -0,0 +1,26 @@ +"""Client layer of the sync docset: PubNub clients (pubnub/pubnub.py, NativeSubscriptionManager).""" +from pubnub.pubnub import PubNub + +from .clients import BaseClients + + +class SyncClients(BaseClients): + client_class = PubNub + + def sync(self, role='open', user_id=None, secret=True): + """A sync client for a role and user ID: clients.sync('open', 'publisher').""" + return self.make(role, user_id, secret) + + def close(self): + pending = [x for x in (self.subscriptions_of(c) for c in self._made if isinstance(c, PubNub)) if x] + for client in self._made: + if not isinstance(client, PubNub): + continue + try: + # Always leave: a sample can subscribe without the test knowing, and a client that stops without + # a leave stays an occupant of the shared channel until the presence timeout. + client.unsubscribe_all() + finally: + client.stop() + self.send_leaves(pending) + self._made = [] diff --git a/tests/live/support/console.py b/tests/live/support/console.py new file mode 100644 index 00000000..2ca71c69 --- /dev/null +++ b/tests/live/support/console.py @@ -0,0 +1,15 @@ +"""quiet_logging(): silence the SDK loggers for a block. Tests that check log output use the caplog fixture instead. +DEBUG logs of the SDK print request URLs, so nothing the tier prints may come from a DEBUG pubnub logger unredacted.""" +import contextlib +import logging + + +@contextlib.contextmanager +def quiet_logging(name='pubnub', level=logging.CRITICAL): + logger = logging.getLogger(name) + before = logger.level + logger.setLevel(level) + try: + yield logger + finally: + logger.setLevel(before) diff --git a/tests/live/support/docs_check.py b/tests/live/support/docs_check.py new file mode 100644 index 00000000..3ce591bb --- /dev/null +++ b/tests/live/support/docs_check.py @@ -0,0 +1,124 @@ +"""Docs cross-check: does every snippet the docs embed from pubnub/python map to a test that runs it? + + python -u tests/live/cli.py docs-check [] [--report-only] [--allow-ref ] + +The checkout comes from the first non-flag argument, then $DOCS_REPO, then ../documentation next to this repository. +It parses every tag in docs/sdks/python/ and docs/sdks/asyncio/ whose url points at pubnub/python and +classifies each requested id (or whole-file embed) as live, compile-only, exception (snippet-exceptions.json) or +NOT COVERED. A covered embed must use the url form refs/heads/master/tests/live/... (or the branch given with +--allow-ref, for a docs preview), the file must exist, docs_extract must find each id in it, and coverage.json must +list the id for that very file. A SHA pin or any other path is NOT COVERED. Exit 1 on NOT COVERED unless --report-only. +The documentation checkout is only read. No network. +""" +import os +import re +from collections import Counter +from pathlib import Path + +from . import LIVE_REL, REPO_ROOT, manifest, snippets + +OUT_OF_SCOPE_PAGES = [ + 'docs/sdks/python/api-reference/users.md', + 'docs/sdks/python/api-reference/spaces.md', + 'docs/sdks/python/api-reference/memberships.md', +] +URL = re.compile(r"url=\{?['\"](https://raw\.githubusercontent\.com/pubnub/python/([^'\"]+))['\"]\}?") +SNIPPETS = re.compile(r'snippets=\{\[([^\]]*)\]\}') +TAG = re.compile(r'') + + +def embeds(root): + out = [] + for sub in ('python', 'asyncio'): + base = root / 'docs' / 'sdks' / sub + if not base.is_dir(): + continue + for md in sorted(base.rglob('*.md*')): + text = md.read_text() + rel = md.relative_to(root).as_posix() + for m in TAG.finditer(text): + tag = m.group(0) + u = URL.search(tag) + if not u: + continue + ids = re.findall(r"['\"]([A-Za-z0-9_/-]+)['\"]", ''.join(SNIPPETS.findall(tag))) + out.append({'docs_file': rel, 'line': text[:m.start()].count('\n') + 1, 'url': u.group(1), + 'tail': u.group(2), 'ids': ids}) + return out + + +def split_tail(tail): + """('refs/heads/' | sha, path) from the part after pubnub/python/.""" + m = re.match(r'refs/heads/(.+?)/(tests/live/.*)$', tail) + if m: + return m.group(1), m.group(2) + m = re.match(r'refs/heads/([^/]+)/(.*)$', tail) + if m: + return m.group(1), m.group(2) + ref, _, path = tail.partition('/') + return ref, path + + +def classify(root, allow_ref=None): + data = manifest.read() or {'files': {}, 'whole_files': {}} + exceptions = manifest.load_exceptions().get('exceptions', []) + results = [] + for e in embeds(root): + if e['docs_file'] in OUT_OF_SCOPE_PAGES: + continue + ref, path = split_tail(e['tail']) + targets = e['ids'] or [None] + for ident in targets: + status, why = 'NOT COVERED', '' + exc = next((x for x in exceptions if x['path'] == path and (x.get('ids') is None or ident in x['ids'])), + None) + if exc: + status, why = 'exception', exc['reason'] + elif not path.startswith(LIVE_REL + '/'): + why = f'path {path} is outside {LIVE_REL}/' + elif ref not in ('master', allow_ref): + why = f'ref {ref} (only master{" or " + allow_ref if allow_ref else ""} is covered)' + elif not (REPO_ROOT / path).exists(): + why = f'{path} does not exist' + elif ident is None: + if path in data.get('whole_files', {}): + status = 'live' + else: + why = 'whole-file embed of a file that no test runs' + elif not snippets.docs_extract((REPO_ROOT / path).read_text(), [ident]): + why = f'docs_extract finds no "{ident}" in {path}' + else: + entry = data['files'].get(path, {}).get(ident) + if entry: + status = entry['mode'] + why = entry.get('test') or entry.get('reason', '') + else: + why = f'coverage.json does not list "{ident}" for {path}' + results.append({**e, 'ref': ref, 'path': path, 'id': ident, 'status': status, 'why': why}) + return results + + +def main(argv): + argv = list(argv) + allow_ref = argv[argv.index('--allow-ref') + 1] if '--allow-ref' in argv else None + positional = [a for i, a in enumerate(argv) if not a.startswith('--') and (i == 0 or argv[i - 1] != '--allow-ref')] + default = os.environ.get('DOCS_REPO') or REPO_ROOT.parent / 'documentation' + root = Path(positional[0]) if positional else Path(default) + if not (root / 'docs' / 'sdks').is_dir(): + print(f'docs-check: {root} is not a documentation checkout') + return 2 + results = classify(root, allow_ref) + counts = Counter(r['status'] for r in results) + refs = Counter(r['ref'] for r in results) + for r in results: + if r['status'] == 'NOT COVERED' and '--verbose' in argv: + print(f'docs-check: NOT COVERED {r["docs_file"]}:{r["line"]} {r["id"] or "(whole file)"}: {r["why"]}') + reasons = Counter(re.sub(r'"[^"]*"|\S+\.py', '...', r['why']) for r in results if r['status'] == 'NOT COVERED') + for reason, n in reasons.most_common(): + print(f'docs-check: NOT COVERED x{n}: {reason}') + by_status = ', '.join(f'{k} {v}' for k, v in sorted(counts.items())) + by_ref = ', '.join(f'{k} {v}' for k, v in sorted(refs.items())) + print(f'docs-check: {len(results)} embedded ids from {root}: {by_status}. Refs: {by_ref}') + if counts.get('NOT COVERED') and '--report-only' not in argv: + return 1 + return 0 diff --git a/tests/live/support/env.py b/tests/live/support/env.py new file mode 100644 index 00000000..3282605d --- /dev/null +++ b/tests/live/support/env.py @@ -0,0 +1,123 @@ +"""Key loader. Fixed env names, grouped in roles. Real env vars win over the optional env file. + +The file is LIVE_ENV_FILE, or tests/live/.env.local when that is not set. The loader never falls back to demo keys and +prints only "set" or "missing" per role. The env names per role are in the Keys table of tests/live/README.md. +""" +import os +from pathlib import Path + +from . import LIVE_DIR, redact + +ROLES = { + 'open': ['PUBLISH_KEY', 'SUBSCRIBE_KEY'], + 'pam': ['PAM_PUBLISH_KEY', 'PAM_SUBSCRIBE_KEY', 'PAM_SECRET_KEY'], + # Read only Admin API access for the preflight. No test uses it. + 'admin': ['PUBNUB_ADMIN_API_KEY'], +} +KEYSET_ROLES = ('open', 'pam') + +# Not secret: keyset ids for the Admin API feature read of the preflight (repository variables in CI). +KEYSET_IDS = {'open': 'DOCS_SNIPPETS_OPEN_KEYSET_ID', 'pam': 'DOCS_SNIPPETS_PAM_KEYSET_ID'} + +# Switches, read from the real environment or the env file. +SWITCHES = ('LIVE_JANITOR', 'LIVE_PREFLIGHT', 'LIVE_GROUP') + +DEFAULT_ENV_FILE = LIVE_DIR / '.env.local' + +_loaded = False + + +def _read_env_file(path): + values = {} + p = Path(path) + if not p.is_file(): + return values + for raw in p.read_text().splitlines(): + line = raw.strip() + if line.startswith('export '): + line = line[len('export '):].strip() + if not line or line.startswith('#') or '=' not in line: + continue + name, _, value = line.partition('=') + values[name.strip()] = value.strip().strip('"').strip("'") + return values + + +def known_names(): + return {n for names in ROLES.values() for n in names} | set(KEYSET_IDS.values()) | set(SWITCHES) + + +def env_file(): + return Path(os.environ.get('LIVE_ENV_FILE') or DEFAULT_ENV_FILE) + + +def load(): + """Fill os.environ from the env file without overriding real env vars. Registers every key with redact.""" + global _loaded + if _loaded: + return + for name, value in _read_env_file(env_file()).items(): + if name in known_names() and not os.environ.get(name): + os.environ[name] = value + for names in ROLES.values(): + for name in names: + redact.register(os.environ.get(name, '')) + _loaded = True + + +def missing(role): + load() + return [name for name in ROLES[role] if not os.environ.get(name)] + + +def has(role): + return not missing(role) + + +def status(): + """One line per role: 'set' or 'missing: NAME, NAME'. Never prints a value.""" + load() + lines = [] + for role in ROLES: + gone = missing(role) + lines.append(f'{role}: ' + ('set' if not gone else 'missing: ' + ', '.join(gone))) + return lines + + +def require(role): + """Return the env values of a role. A missing key fails with the exact names, there is no fallback.""" + gone = missing(role) + if gone: + names = ', '.join(gone) + raise RuntimeError(f'role {role!r} is missing env: {names}. Set them in the environment or in ' + 'tests/live/.env.local (see .env.example).') + return {name: os.environ[name] for name in ROLES[role]} + + +def keyset_id(role): + load() + return os.environ.get(KEYSET_IDS[role], '').strip() + + +def switch_on(name): + """LIVE_JANITOR and LIVE_PREFLIGHT are on unless set to off.""" + load() + return os.environ.get(name, '').strip().lower() != 'off' + + +def use_open_keys(pnconfig): + """Hidden line helper: put the open keyset keys on a sample's own PNConfiguration.""" + keys = require('open') + pnconfig.publish_key = keys['PUBLISH_KEY'] + pnconfig.subscribe_key = keys['SUBSCRIBE_KEY'] + return pnconfig + + +def use_pam_keys(pnconfig, secret=True): + """Hidden line helper: put the Access Manager keyset keys on a sample's own PNConfiguration.""" + keys = require('pam') + pnconfig.publish_key = keys['PAM_PUBLISH_KEY'] + pnconfig.subscribe_key = keys['PAM_SUBSCRIBE_KEY'] + if secret: + pnconfig.secret_key = keys['PAM_SECRET_KEY'] + return pnconfig diff --git a/tests/live/support/explain.py b/tests/live/support/explain.py new file mode 100644 index 00000000..c34cd78c --- /dev/null +++ b/tests/live/support/explain.py @@ -0,0 +1,45 @@ +"""pytest plugin: a failed test (or setup or teardown) whose exception is, or wraps through __cause__ or __context__, a +PubNub SDK error gets a "PubNub error" section with category, status code, operation and the service's error data. +Everything goes through redact.scrub, because SDK errors can carry request URLs.""" +import pytest +from pubnub.exceptions import PubNubAsyncioException, PubNubException + +from . import redact + + +def _chain(error): + seen = set() + while error is not None and id(error) not in seen: + seen.add(id(error)) + yield error + error = error.__cause__ or error.__context__ + + +def describe(error): + for e in _chain(error): + if isinstance(e, (PubNubException, PubNubAsyncioException)): + status = getattr(e, 'status', None) + parts = [f'type={type(e).__name__}'] + if isinstance(e, PubNubException): + parts.append(f'status_code={e.get_status_code()}') + parts.append(f'pn_error={getattr(e, "_pn_error", None)}') + if status is not None: + category = getattr(status, 'category', None) + parts.append(f'category={getattr(category, "name", category)}') + parts.append(f'operation={getattr(status, "operation", None)}') + parts.append(f'status_code={getattr(status, "status_code", None)}') + error_data = getattr(status, 'error_data', None) + if error_data is not None: + parts.append(f'error_data={getattr(error_data, "information", error_data)}') + return redact.scrub(', '.join(parts)) + return None + + +@pytest.hookimpl(hookwrapper=True) +def pytest_runtest_makereport(item, call): + outcome = yield + report = outcome.get_result() + if report.failed and call.excinfo is not None: + text = describe(call.excinfo.value) + if text: + report.sections.append((f'PubNub error ({report.when})', text)) diff --git a/tests/live/support/extractor.py b/tests/live/support/extractor.py new file mode 100644 index 00000000..b4ce2d82 --- /dev/null +++ b/tests/live/support/extractor.py @@ -0,0 +1,72 @@ +"""Equivalence check of the Python extractor (support/snippets.py) against the docs function. + + python -u tests/live/cli.py extractor --regen + +runs extractSnippets() of /src/helper/codeSnippetFetcher.ts with `npx tsx` (from the docs checkout, read only) +on every case below and writes the outputs to support/extractor_fixtures.json. CI has no docs checkout, so the lint +self-test compares the Python extractor against the stored outputs. +""" +import json +import subprocess +import tempfile +from pathlib import Path + +FIXTURES_FILE = Path(__file__).resolve().parent / 'extractor_fixtures.json' + +CASES = [ + ('plain', '# snippet.a\nx = 1\n# snippet.end\n', ['a']), + ('indented', 'def f():\n # snippet.a\n x = 1\n if x:\n y = 2\n # snippet.end\n', ['a']), + ('nested start ends the outer', '# snippet.a\nx = 1\n# snippet.b\ny = 2\n# snippet.end\n', ['a']), + ('nested start, inner id', '# snippet.a\nx = 1\n# snippet.b\ny = 2\n# snippet.end\n', ['b']), + ('no space after hash is not a marker', '#snippet.a\nx = 1\n#snippet.end\n', ['a']), + ('two spaces after hash', '# snippet.a\nx = 1\n# snippet.end\n', ['a']), + ('id with a slash', '# snippet.a/b\nx = 1\n# snippet.end\n', ['a/b']), + ('hide and show', '# snippet.a\nx = 1\n# snippet.hide\nsecret = 2\n# snippet.show\ny = 3\n# snippet.end\n', ['a']), + ('blank lines with whitespace', ' # snippet.a\n x = 1\n \n\n y = 2\n # snippet.end\n', ['a']), + ('tabs', '\t# snippet.a\n\tx = 1\n\t\ty = 2\n\t# snippet.end\n', ['a']), + ('blueprint line', '# snippet.a\nx = 1\n# blueprint._o945md2\ny = 2\n# snippet.end\n', ['a']), + ('empty region', '# snippet.a\n# snippet.end\n', ['a']), + ('missing id', '# snippet.a\nx = 1\n# snippet.end\n', ['zzz']), + ('runs to the end of the file', 'z = 0\n# snippet.a\nx = 1\ny = 2\n', ['a']), + ('first start marker wins', '# snippet.a\nx = 1\n# snippet.end\n# snippet.a\nx = 2\n# snippet.end\n', ['a']), + ('two ids in one call', '# snippet.a\nx = 1\n# snippet.end\n# snippet.b\ny = 2\n# snippet.end\n', ['a', 'b']), + ('trailing spaces on markers', '# snippet.a \nx = 1\n# snippet.end \n', ['a']), + ('carriage returns', '# snippet.a\r\nx = 1\r\n# snippet.end\r\n', ['a']), + ('other prefix ends the region', '# snippet.a\nx = 1\n// snippet.b\ny = 2\n# snippet.end\n', ['a']), + ('same id with another prefix is no boundary', '# snippet.a\nx = 1\n// snippet.a\ny = 2\n# snippet.end\n', ['a']), + ('end marker of another prefix', '# snippet.a\nx = 1\n// snippet.end\ny = 2\n# snippet.end\n', ['a']), + ('hide without show', '# snippet.a\nx = 1\n# snippet.hide\ny = 2\n# snippet.end\n', ['a']), +] + +TS = r''' +import { extractSnippets } from '%s'; +import fs from 'node:fs'; +const cases = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); +const prefixes = ['// ', '# ', '/* ', '