function test_graph_client
A test function that validates the SharePoint Graph API client by testing authentication, document listing, and file download capabilities.
/tf/active/vicechatdev/SPFCsync/test_graph_client.py
15 - 70
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_clientconfig
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 returns both success status and document count, allowing callers to verify both connectivity and data availability
- Consider running this test in a non-production environment first to avoid rate limiting or unexpected data access
- The hex preview of downloaded content is limited to 50 bytes to avoid overwhelming console output
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_rest_client 83.6% similar
-
function quick_test 80.8% similar
-
function main_v37 80.4% similar
-
function test_graph_api_access 80.3% similar
-
function test_filecloud_integration 77.0% similar