azure-container-networking
azure-container-networking copied to clipboard
Add unit tests for createHostNCApipaNetwork() function and apply changes from PR #3693
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
vEthernethostNCLoopbackAdapterNameconstant 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
- ✅
hostNCLoopbackAdapterNameexists: Should skip creation - ✅
vEthernethostNCLoopbackAdapterNameexists: 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.