🔍 Code Extractor

function create_test_file_v1

Maturity: 39

Creates a temporary test file with specified content and filename in a temporary directory.

File:
/tf/active/vicechatdev/SPFCsync/test_upload_modalities.py
Lines:
27 - 35
Complexity:
simple

Purpose

This utility function is designed for testing purposes, particularly for file upload operations. It creates a temporary file in a system-generated temporary directory, writes the provided content to it, and returns the full file path. This is useful for unit tests, integration tests, or any scenario where temporary test files are needed without polluting the main file system.

Source Code

def create_test_file(content="Test file content", filename="test_upload.txt"):
    """Create a temporary test file"""
    temp_dir = tempfile.mkdtemp()
    file_path = os.path.join(temp_dir, filename)
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    return file_path

Parameters

Name Type Default Kind
content - 'Test file content' positional_or_keyword
filename - 'test_upload.txt' positional_or_keyword

Parameter Details

content: String content to write into the test file. Defaults to 'Test file content'. Can be any string value including multi-line text. The content is written with UTF-8 encoding.

filename: Name of the file to create in the temporary directory. Defaults to 'test_upload.txt'. Should include the file extension. Can be any valid filename string.

Return Value

Returns a string representing the absolute file path to the created temporary test file. The path includes the temporary directory path and the specified filename (e.g., '/tmp/tmpXXXXXX/test_upload.txt' on Unix systems). The file exists on disk and contains the specified content when the function returns.

Dependencies

  • tempfile
  • os

Required Imports

import tempfile
import os

Usage Example

import os
import tempfile

def create_test_file(content="Test file content", filename="test_upload.txt"):
    """Create a temporary test file"""
    temp_dir = tempfile.mkdtemp()
    file_path = os.path.join(temp_dir, filename)
    
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    return file_path

# Example 1: Create a test file with default content
file_path = create_test_file()
print(f"Created test file at: {file_path}")

# Example 2: Create a test file with custom content
custom_content = "This is my custom test content\nWith multiple lines"
file_path = create_test_file(content=custom_content, filename="my_test.txt")
print(f"Created custom test file at: {file_path}")

# Example 3: Use in a test scenario
file_path = create_test_file(content="Sample data", filename="data.csv")
try:
    # Perform file operations or tests
    with open(file_path, 'r') as f:
        data = f.read()
        print(f"File content: {data}")
finally:
    # Clean up: remove the file and directory
    import shutil
    temp_dir = os.path.dirname(file_path)
    shutil.rmtree(temp_dir)

Best Practices

  • Remember to clean up the temporary directory and file after use. The function creates a new temporary directory each time it's called, which won't be automatically deleted.
  • Use shutil.rmtree() to remove the entire temporary directory (os.path.dirname(file_path)) when done with the test file.
  • Consider wrapping file operations in try-finally blocks to ensure cleanup happens even if tests fail.
  • The function uses UTF-8 encoding by default, which is suitable for most text content. Be aware of this if testing with binary files.
  • Each call creates a new temporary directory, so multiple calls will create multiple directories that need separate cleanup.
  • The temporary directory location is system-dependent (e.g., /tmp on Unix, C:\Users\...\AppData\Local\Temp on Windows).
  • For pytest or unittest, consider using fixtures or setUp/tearDown methods to manage file creation and cleanup automatically.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_test_file 78.4% similar

    Creates a temporary text file with predefined multi-chapter test content for testing document extraction and processing functionality.

    From: /tf/active/vicechatdev/vice_ai/test_extraction_debug.py
  • function create_test_document 75.8% similar

    Creates a text file at the specified path with the given content, primarily used for testing purposes.

    From: /tf/active/vicechatdev/docchat/test_incremental_indexing.py
  • function modify_test_document 56.5% similar

    Modifies the content of a test document file by writing new content to it, with a built-in delay to ensure the file's modification time changes.

    From: /tf/active/vicechatdev/docchat/test_incremental_indexing.py
  • function test_filecloud_operations 56.0% similar

    Tests FileCloud basic operations by creating a test folder to verify connectivity and authentication with a FileCloud server.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
  • function create_test_dataset 55.0% similar

    Creates a test CSV dataset with sample product sales data across different regions and months, saving it to a temporary file.

    From: /tf/active/vicechatdev/vice_ai/test_integration.py
← Back to Browse