API Integration Tests

This directory contains Python API integration tests for Connect endpoints using Bravado and the Swagger specification.

Directory structure

docs/api/tests/
├── test_*.py               - API integration tests (one per API domain)
├── conftest.py             - Pytest configuration
├── connect_manager.py      - Connect server management
├── helper_connect_api.py   - Base test class (ConnectAPITest)
├── content_helpers.py      - Content creation helpers (UserClientMixin)
├── factories.py            - Test data factories
├── test_coverage.py        - Validates every public API has a test
└── helper_*.py             - Various helper modules

Swagger specs

API definitions are in docs/api/src/{section}/{section}.yaml using Swagger 2.0 format with extensions:

  • x-visibility - public, experimental, or internal
  • x-nullable - field can be null
  • readOnly - field only in responses, not requests

Test function names must match the operationId from the spec. The test_coverage.py file validates that every public API has at least one test_<operationId>... test.

User roles

The three valid user roles are administrator, publisher, and viewer. Anonymous represents unauthenticated requests (no user account), not an actual role.

When testing permissions, order tests from most privileged to least: administrator → publisher → viewer → anonymous.

Test file structure

from bravado.exception import (
    HTTPBadRequest,
    HTTPUnauthorized,
    HTTPForbidden,
    HTTPNotFound,
)

from helper_connect_api import ConnectAPITest
from content_helpers import UserClientMixin
import apierror


class TestFeatureName(ConnectAPITest, UserClientMixin):
    """Test the v1 API for [feature description]."""

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.createUsers()
        cls.createClients()
        # Additional setup...

    # Tests go here...

Test naming convention

test_<operationId>_<scenario>

Examples: - test_listUsers_viewer - List users as viewer - test_createContent_invalidName - Create with invalid name - test_deleteKey_notFound - Delete non-existent key - test_getUser_anonymous - Get user without auth

Available test clients

The UserClientMixin provides these clients after calling createUsers() and createClients():

  • self.clients.administrator - Administrator role
  • self.clients.publisher - Publisher role
  • self.clients.viewer - Viewer role
  • self.clients.anonymous - No authentication (unauthenticated)

Access user objects via: - self.administrator - Administrator user object - self.publisher - Publisher user object - self.viewer - Viewer user object

Raw API requests

For invalid inputs that bypass Bravado validation, use raw_api_request:

response = self.raw_api_request(
    server_address=self.manager.server_address,
    uri="/__api__/v1/endpoint",
    params={"invalid_param": "value"},
    assert_on_failure=False,
)
self.assertEqual(response.status_code, 400)

With request body:

import requests

response = self.raw_api_request(
    server_address=self.manager.server_address,
    uri="/__api__/v1/endpoint",
    request_data={"field": "value"},
    method=requests.post,
)

Use get_uri_for() to get URIs from bravado operations instead of hardcoding:

response = self.raw_api_request(
    server_address=self.manager.server_address,
    uri=self.get_uri_for(self.client.instrumentation.getShinyAppUsage),
    params={"content_guid": "invalid-guid"},
    assert_on_failure=False,
)

Model comparisons

When comparing models from different bravado clients, use assertEqualByFields() to avoid type mismatch errors:

user1 = self.client.users.getUser(id).result()
user2 = self.clients.viewer.users.getUser(id).result()
# self.assertEqual(user1, user2)  # Fails - different types
self.assertEqualByFields(user1, user2)  # Works - compares field values

Binary file uploads

For endpoints that accept binary data, use io.BytesIO:

import io

# Upload binary content
client.uploading.upload(body=io.BytesIO(binary_data)).result()

# Or open a file
with open("archive.tar.gz", "rb") as f:
    client.uploading.upload(body=f).result()

Cleanup patterns

Pattern When to Use
setUp/tearDown Default. Each test needs isolated resources
setUpClass/tearDownClass Expensive shared fixtures that tests only read
addCleanup() Per-test cleanup when modifying shared fixtures

addCleanup with Bravado API calls

Wrap Bravado calls in a lambda to defer execution until cleanup:

# WRONG - executes immediately, .result never called
self.addCleanup(client.api.delete(guid=guid).result)

# CORRECT - deferred execution
self.addCleanup(lambda: client.api.delete(guid=guid).result())

Running tests

# Run all API tests
just docs/api/test

# Run specific file
TEST_ARGS="tests/test_keys.py" just docs/api/test

# Run specific test class
TEST_ARGS="tests/test_keys.py::TestAPIKey" just docs/api/test

# Run specific test function
TEST_ARGS="tests/test_keys.py::TestAPIKey::test_listKeys_viewer" just docs/api/test

Quality criteria

Criteria Good Fair Poor
Permission matrix All 4 roles 2-3 roles 1 role
Error cases 400, 401, 403, 404 Some errors None
Response validation Structure + data Structure only Status code only
Data persistence Verified with GET Assumed Not checked

Best practices

  1. Tests API via HTTP - If not, it may belong in backend unit tests
  2. Permission matrix complete - Tests ALL four roles in order: administrator → publisher → viewer → anonymous
  3. Validates response structure - Not just status codes, but response body content
  4. Tests ALL error cases - Every documented error code in the Swagger spec (400, 401, 403, 404, 409, etc.)
  5. Verifies persistence - Follow-up GET confirms side effects
  6. Uses Bravado - Ensures Swagger spec compliance
  7. Exact assertions - Assert exact values when test data is controlled, not ranges or minimums

Anti-patterns

  1. Weak assertions - Don’t use ranges or minimums (e.g., >= 1) when exact values are known
  2. Status code only tests - Always validate response body, not just status codes
  3. Single role testing - Test the full permission matrix (all 4 roles in order)
  4. Missing error cases - Test unhappy paths (400, 404, 409, etc.)
  5. Hardcoded IDs - Use dynamically created objects, not hardcoded GUIDs
  6. Missing persistence verification - Verify side effects with follow-up GET requests
  7. Shared state mutation - Don’t modify class-level fixtures in individual tests
  8. Missing cleanup - Clean up created resources or use unique names
  9. Bypassing Bravado unnecessarily - Use Bravado for Swagger spec compliance; use rawApiRequest only for invalid inputs