🔍 Code Extractor

function test_rest_client

Maturity: 44

A test function that validates the SharePoint REST API client by testing authentication, document listing, and file download capabilities.

File:
/tf/active/vicechatdev/SPFCsync/test_rest_client.py
Lines:
16 - 59
Complexity:
moderate

Purpose

This function serves as an integration test for the SharePointRestClient class. It verifies that the client can successfully authenticate with SharePoint using Azure credentials, retrieve a list of documents from a specified SharePoint path, and download file content. The function provides detailed console output showing the test progress and results, making it useful for debugging and validation during development or deployment.

Source Code

def test_rest_client():
    """Test the REST-based SharePoint client."""
    print("Testing SharePoint REST API Client")
    print("=" * 40)
    
    try:
        from sharepoint_rest_client import SharePointRestClient
        from config import Config
        
        print("Creating SharePoint REST client...")
        client = SharePointRestClient(
            Config.SHAREPOINT_SITE_URL,
            Config.AZURE_CLIENT_ID,
            Config.AZURE_CLIENT_SECRET
        )
        
        print("✅ SharePoint REST client created successfully")
        
        # Test document listing
        print("\nTesting document listing...")
        documents = client.get_all_documents(Config.SHAREPOINT_DOCUMENTS_PATH)
        print(f"✅ Found {len(documents)} documents")
        
        if documents:
            print("\nSample documents:")
            for doc in documents[:3]:  # Show first 3
                print(f"  - {doc['name']} (size: {doc['size']} bytes, modified: {doc['modified']})")
            if len(documents) > 3:
                print(f"  ... and {len(documents) - 3} more")
        
        # Test file download (if there are documents)
        if documents:
            print(f"\nTesting file download for: {documents[0]['name']}")
            content = client.download_file_content(documents[0]['server_relative_url'])
            if content:
                print(f"✅ Successfully downloaded {len(content)} bytes")
            else:
                print("❌ Failed to download file content")
        
        return True
        
    except Exception as e:
        print(f"❌ SharePoint REST client failed: {e}")
        return False

Return Value

Returns a boolean value: True if all SharePoint REST client operations (initialization, document listing, and file download) succeed without exceptions; False if any exception occurs during testing. The return value can be used to determine if the SharePoint integration is properly configured.

Dependencies

  • sharepoint_rest_client
  • config

Required Imports

from sharepoint_rest_client import SharePointRestClient
from config import Config

Conditional/Optional Imports

These imports are only needed under specific conditions:

from sharepoint_rest_client import SharePointRestClient

Condition: imported inside try block, only loaded when function executes

Required (conditional)
from config import Config

Condition: imported inside try block, only loaded when function executes

Required (conditional)

Usage Example

# Ensure config.py has required settings:
# SHAREPOINT_SITE_URL = 'https://yourcompany.sharepoint.com/sites/yoursite'
# AZURE_CLIENT_ID = 'your-client-id'
# AZURE_CLIENT_SECRET = 'your-client-secret'
# SHAREPOINT_DOCUMENTS_PATH = 'Shared Documents'

# Run the test
result = test_rest_client()

if result:
    print('SharePoint REST client test passed')
else:
    print('SharePoint REST client test failed')

# Example output:
# Testing SharePoint REST API Client
# ========================================
# Creating SharePoint REST client...
# ✅ SharePoint REST client created successfully
# Testing document listing...
# ✅ Found 5 documents
# Sample documents:
#   - report.pdf (size: 1024000 bytes, modified: 2024-01-15)
#   - data.xlsx (size: 512000 bytes, modified: 2024-01-14)

Best Practices

  • Ensure all required configuration values are set in config.py before running this test
  • The function prints detailed output to console, making it suitable for manual testing and debugging
  • The test downloads actual file content, so ensure network connectivity and proper permissions
  • Consider running this test in a non-production environment to avoid unnecessary API calls
  • The function catches all exceptions broadly, so check console output for specific error details
  • Only the first 3 documents are displayed in the sample output to avoid console clutter
  • The function tests with the first document found, ensure at least one document exists in the SharePoint path for full test coverage

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_graph_client 83.6% similar

    A test function that validates the SharePoint Graph API client by testing authentication, document listing, and file download capabilities.

    From: /tf/active/vicechatdev/SPFCsync/test_graph_client.py
  • function test_sharepoint_api_call 78.1% similar

    Tests SharePoint REST API connectivity by making an authenticated GET request to retrieve basic site information and validates the access token and permissions.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
  • function main_v36 77.3% similar

    Main test function that validates SharePoint REST API connectivity by loading configuration, setting up logging, and executing REST client tests.

    From: /tf/active/vicechatdev/SPFCsync/test_rest_client.py
  • function test_sharepoint_listing 76.8% similar

    Tests the SharePoint document listing functionality by connecting to a SharePoint site and retrieving all documents from a specified path.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
  • function test_sharepoint_with_token 76.2% similar

    Tests SharePoint REST API connectivity and authentication by making a GET request to retrieve site information using a provided access token.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_permissions.py
← Back to Browse