Back to Repositories

Testing Atomic File Operations in OpenPilot

This test suite validates the atomic file writing functionality in OpenPilot’s common utilities. It focuses on ensuring safe file operations by testing atomic write operations that prevent partial or corrupted writes.

Test Coverage Overview

The test suite provides comprehensive coverage of atomic file writing operations in OpenPilot.

Key areas tested include:
  • Temporary file creation during write operations
  • File content integrity verification
  • Proper file cleanup after operations
  • Directory-based atomic writes
Integration points focus on filesystem operations and temporary file handling.

Implementation Analysis

The testing approach uses a modular design with a reusable test function that validates atomic write operations. It employs Python’s context manager pattern through the ‘with’ statement to ensure proper resource handling and cleanup.

The implementation uses UUID generation for unique temporary files and leverages Python’s built-in file operations for verification.

Technical Details

Testing tools and components include:
  • Python’s os module for file operations
  • UUID4 for unique file name generation
  • Context managers for resource handling
  • Temporary file operations in /tmp directory
  • Assertion-based verification

Best Practices Demonstrated

The test suite exemplifies several testing best practices including proper resource cleanup, isolation of test cases, and verification of both intermediate and final states.

Notable practices include:
  • Atomic operation verification
  • Temporary resource management
  • Explicit cleanup procedures
  • Reusable test functions

commaai/openpilot

common/tests/test_file_helpers.py

            
import os
from uuid import uuid4

from openpilot.common.file_helpers import atomic_write_in_dir


class TestFileHelpers:
  def run_atomic_write_func(self, atomic_write_func):
    path = f"/tmp/tmp{uuid4()}"
    with atomic_write_func(path) as f:
      f.write("test")
      assert not os.path.exists(path)

    with open(path) as f:
      assert f.read() == "test"
    os.remove(path)

  def test_atomic_write_in_dir(self):
    self.run_atomic_write_func(atomic_write_in_dir)