function test_folder_structure
Tests SharePoint folder structure by listing root-level folders, displaying their contents, and providing a summary of total folders and documents.
/tf/active/vicechatdev/SPFCsync/test_folder_structure.py
16 - 81
moderate
Purpose
This function serves as a diagnostic and testing utility for SharePoint integration. It creates a SharePoint Graph client, retrieves all root-level folders, displays detailed information about the first three folders including their documents, and provides a summary count of total folders and documents. It's designed to verify SharePoint connectivity and explore the document library structure with formatted console output.
Source Code
def test_folder_structure():
"""Test listing folders and their structure."""
print("Testing SharePoint Folder Structure")
print("=" * 50)
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")
print()
# Get all folders at root level
print("š ROOT LEVEL FOLDERS:")
print("-" * 30)
folders = get_root_folders(client)
if folders:
for i, folder in enumerate(folders, 1):
print(f"{i:2d}. {folder['name']}")
print(f" š {folder['item_count']} items")
if folder.get('modified'):
print(f" š
Modified: {folder['modified']}")
print()
else:
print("No folders found at root level")
# Get detailed file listing for first few folders
print("\nš DETAILED FOLDER CONTENTS:")
print("-" * 40)
for folder in folders[:3]: # Show first 3 folders
print(f"\nš {folder['name']}:")
folder_docs = get_folder_documents(client, folder['name'])
if folder_docs:
print(f" Found {len(folder_docs)} documents:")
for doc in folder_docs[:5]: # Show first 5 docs
print(f" š {doc['name']} ({doc['size']} bytes)")
if len(folder_docs) > 5:
print(f" ... and {len(folder_docs) - 5} more files")
else:
print(" No documents found")
# Compare with total document count
print("\nš SUMMARY:")
print("-" * 20)
all_documents = client.get_all_documents("/")
print(f"Total folders found: {len(folders)}")
print(f"Total documents across all folders: {len(all_documents)}")
return True, folders, all_documents
except Exception as e:
print(f"ā Folder structure test failed: {e}")
import traceback
traceback.print_exc()
return False, [], []
Return Value
Returns a tuple containing three elements: (1) Boolean indicating success (True) or failure (False) of the test, (2) List of folder dictionaries containing folder metadata (name, item_count, modified date), (3) List of all documents found across all folders. On failure, returns (False, [], []).
Dependencies
sharepoint_graph_clientconfigrequeststraceback
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 operations
Required (conditional)from config import Config
Condition: imported inside try block, required for configuration settings
Required (conditional)import traceback
Condition: imported inside except block for error reporting
Required (conditional)Usage Example
# Ensure config.py has required settings:
# Config.SHAREPOINT_SITE_URL = 'https://yourcompany.sharepoint.com/sites/yoursite'
# Config.AZURE_CLIENT_ID = 'your-client-id'
# Config.AZURE_CLIENT_SECRET = 'your-client-secret'
# Ensure helper functions are defined:
# def get_root_folders(client): ...
# def get_folder_documents(client, folder_name): ...
# Run the test
success, folders, all_documents = test_folder_structure()
if success:
print(f'Test passed! Found {len(folders)} folders and {len(all_documents)} documents')
for folder in folders:
print(f"Folder: {folder['name']} with {folder['item_count']} items")
else:
print('Test failed - check error output above')
Best Practices
- This function requires helper functions get_root_folders() and get_folder_documents() to be defined in the same module
- Ensure Azure AD application has appropriate permissions to access SharePoint sites and read documents
- The function prints output directly to console - redirect stdout if you need to capture output programmatically
- Only the first 3 folders and first 5 documents per folder are displayed in detail to avoid overwhelming output
- The function catches all exceptions and prints traceback for debugging - review error messages carefully
- Returns empty lists on failure, so always check the boolean success flag before processing results
- Consider implementing pagination if dealing with SharePoint sites containing thousands of folders or documents
- The function uses client.get_all_documents('/') which may be slow for large document libraries
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function analyze_structure 80.9% similar
-
function main_v21 78.7% similar
-
function quick_test 77.0% similar
-
function main_v35 74.3% similar
-
function get_root_folders 73.3% similar