šŸ” Code Extractor

function test_folder_structure

Maturity: 46

Tests SharePoint folder structure by listing root-level folders, displaying their contents, and providing a summary of total folders and documents.

File:
/tf/active/vicechatdev/SPFCsync/test_folder_structure.py
Lines:
16 - 81
Complexity:
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_client
  • config
  • requests
  • traceback

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function analyze_structure 80.9% similar

    Analyzes and reports on the folder structure of a SharePoint site, displaying folder paths, file counts, and searching for expected folder patterns.

    From: /tf/active/vicechatdev/SPFCsync/analyze_structure.py
  • function main_v21 78.7% similar

    Main test function that validates SharePoint folder structure connectivity and configuration, comparing actual folders against expected structure.

    From: /tf/active/vicechatdev/SPFCsync/test_folder_structure.py
  • function quick_test 77.0% 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 main_v35 74.3% similar

    A diagnostic function that explores SharePoint site structure to investigate why only 2 folders are visible when more are expected in the web interface.

    From: /tf/active/vicechatdev/SPFCsync/diagnostic_comprehensive.py
  • function get_root_folders 73.3% similar

    Retrieves all folders at the root level of a SharePoint drive using Microsoft Graph API, returning their metadata including name, ID, item count, timestamps, and web URL.

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