🔍 Code Extractor

function test_graph_client

Maturity: 46

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

File:
/tf/active/vicechatdev/SPFCsync/test_graph_client.py
Lines:
15 - 70
Complexity:
moderate

Purpose

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

Source Code

def test_graph_client():
    """Test the Graph API SharePoint client."""
    print("Testing SharePoint Graph API Client")
    print("=" * 40)
    
    try:
        from sharepoint_graph_client import SharePointGraphClient
        from config import Config
        
        print("Creating SharePoint Graph client...")
        client = SharePointGraphClient(
            Config.SHAREPOINT_SITE_URL,
            Config.AZURE_CLIENT_ID,
            Config.AZURE_CLIENT_SECRET
        )
        
        print("✅ SharePoint Graph client created successfully")
        
        # Test document listing
        print("\nTesting document listing...")
        documents = client.get_all_documents("/")
        print(f"✅ Found {len(documents)} documents")
        
        if documents:
            print("\nSample documents:")
            for i, doc in enumerate(documents[:5]):  # Show first 5
                print(f"  {i+1}. {doc['name']}")
                print(f"     Size: {doc['size']} bytes")
                print(f"     Modified: {doc['modified']}")
                print(f"     Path: {doc['relative_path']}")
                print()
            
            if len(documents) > 5:
                print(f"  ... and {len(documents) - 5} more documents")
        
        # Test file download (if there are documents)
        if documents:
            test_doc = documents[0]
            print(f"\nTesting file download for: {test_doc['name']}")
            content = client.download_file_content(test_doc['server_relative_url'])
            if content:
                print(f"✅ Successfully downloaded {len(content)} bytes")
                
                # Show first few bytes as hex (for verification)
                preview = content[:50].hex() if len(content) >= 50 else content.hex()
                print(f"   Content preview (hex): {preview}...")
            else:
                print("❌ Failed to download file content")
        
        return True, len(documents) if documents else 0
        
    except Exception as e:
        print(f"❌ SharePoint Graph client failed: {e}")
        import traceback
        traceback.print_exc()
        return False, 0

Return Value

Returns a tuple containing two elements: (1) a boolean indicating whether the test passed (True) or failed (False), and (2) an integer representing the number of documents found in SharePoint (0 if the test failed or no documents exist).

Dependencies

  • sharepoint_graph_client
  • config

Required Imports

from sharepoint_graph_client import SharePointGraphClient
from config import Config
import traceback

Conditional/Optional Imports

These imports are only needed under specific conditions:

from sharepoint_graph_client import SharePointGraphClient

Condition: imported inside try block, required for SharePoint Graph API operations

Required (conditional)
from config import Config

Condition: imported inside try block, required for configuration settings

Required (conditional)
import traceback

Condition: used in exception handling to print detailed error information

Required (conditional)

Usage Example

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

# Run the test
success, doc_count = test_graph_client()

if success:
    print(f'Test passed! Found {doc_count} documents.')
else:
    print('Test failed. Check error output above.')

Best Practices

  • Ensure Azure AD application has proper permissions (Sites.Read.All or Sites.ReadWrite.All) before running this test
  • The function prints detailed output to console, making it suitable for interactive testing but not for production logging
  • The test downloads the first document found, which may consume bandwidth for large files
  • Exception handling is comprehensive with traceback printing for debugging
  • The function tests only the root directory ('/') - modify the path parameter in get_all_documents() to test other directories
  • Returns a tuple for programmatic validation, allowing integration into larger test suites
  • Consider adding timeout handling for slow network connections or large file downloads
  • The hex preview of downloaded content is limited to 50 bytes to avoid console clutter

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_rest_client 83.6% similar

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

    From: /tf/active/vicechatdev/SPFCsync/test_rest_client.py
  • function main_v8 80.9% similar

    Main test function that validates SharePoint Graph API integration, tests the Graph client connection, and verifies FileCloud sync functionality.

    From: /tf/active/vicechatdev/SPFCsync/test_graph_client.py
  • function quick_test 80.8% similar

    A diagnostic function that tests SharePoint Graph API connectivity and verifies access to the main site library by checking for expected folder structures in the root directory.

    From: /tf/active/vicechatdev/SPFCsync/quick_test.py
  • function test_graph_api_access 80.3% similar

    Tests Microsoft Graph API access by obtaining an OAuth2 token and verifying connectivity to check tenant settings for SharePoint integration.

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
  • function test_filecloud_integration 77.0% similar

    Integration test function that verifies the SharePoint Graph API client works correctly with FileCloud synchronization service by creating a sync service instance and testing document retrieval.

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