azure-container-networking icon indicating copy to clipboard operation
azure-container-networking copied to clipboard

Add unit tests for createHostNCApipaNetwork() function and apply changes from PR #3693

Open Copilot opened this issue 5 months ago • 2 comments

This PR addresses the follow-up work for PR #3693 by adding comprehensive unit tests and applying the necessary changes to the createHostNCApipaNetwork() function.

Changes Made

1. Applied Changes from PR #3693

  • Added vEthernethostNCLoopbackAdapterName constant for the vEthernet interface name: "vEthernet (LoopbackAdapterHostNCConnectivity)"
  • Updated createHostNCApipaNetwork() logic to check for both loopback adapter interfaces before creating a new one
  • Fixed typo in comment: "fitst" → "first"

2. Code Refactoring for Testability

  • Extracted interface existence logic into a pure function shouldCreateLoopbackAdapter() that can be easily unit tested
  • This function takes an interface existence checker as a parameter, enabling dependency injection for testing

3. Comprehensive Unit Tests

Added TestShouldCreateLoopbackAdapter() that covers all scenarios:

  • Neither interface exists: Should create loopback adapter
  • hostNCLoopbackAdapterName exists: Should skip creation
  • vEthernethostNCLoopbackAdapterName exists: Should skip creation
  • Both interfaces exist: Should skip creation (prioritizes hostNCLoopbackAdapterName)

4. Additional Tests

  • Added TestConstants() to validate the vEthernet constant is constructed correctly
  • Added Windows build constraints to ensure Windows-specific code only runs on Windows

Code Example

The new logic checks for both interface types:

// Before (PR #3693)
if interfaceExists, _ := networkcontainers.InterfaceExists(hostNCLoopbackAdapterName); !interfaceExists {
    // create adapter
}

// After (this PR) 
shouldCreate, logMessage := shouldCreateLoopbackAdapter(networkcontainers.InterfaceExists)
logger.Printf(logMessage)
if shouldCreate {
    // create adapter
}

The extracted function enables comprehensive testing:

func shouldCreateLoopbackAdapter(interfaceExistsFunc func(string) (bool, error)) (bool, string) {
    loopbackInterfaceExists, _ := interfaceExistsFunc(hostNCLoopbackAdapterName)
    vethernetLoopbackInterfaceExists, _ := interfaceExistsFunc(vEthernethostNCLoopbackAdapterName)
    
    if loopbackInterfaceExists {
        return false, hostNCLoopbackAdapterName + " already created, skipping loopback interface creation"
    }
    if vethernetLoopbackInterfaceExists {
        return false, vEthernethostNCLoopbackAdapterName + " already created, skipping loopback interface creation"
    }
    
    return true, "Creating loopback adapter"
}

Fixes #3694.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot avatar May 30 '25 22:05 Copilot